django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

Detect underlying field for OneToOne primary key

Open schferbe opened this issue 3 years ago • 7 comments

Description

When using a OneToOneField as a primary key it does not get serialized in the same way as the "parent" model. E.g.

        class MyModelA(models.Model):
            id = models.DecimalField(max_digits=4, decimal_places=2, primary_key=True)

        class MyModelB(models.Model):
            id = models.OneToOneField(MyModelA, models.CASCADE, primary_key=True)

        class MyModelASerializer(serializers.ModelSerializer):
            class Meta:
                model = MyModelA
                fields = "__all__"

        class MyModelBSerializer(serializers.ModelSerializer):
            class Meta:
                model = MyModelB
                fields = "__all__"

The following serializations would result

MyModelASerializer().to_representation(MyModelA(id=12.34))
# {"id": "12.24"}
MyModelBSerializer().to_representation(MyModelB(id=MyModelA(id=12.34)))
# {"id": 12.24}

This PR sets the pk_field attribute of the PrimaryKeyRelatedField to ensure serialization is consistent with the "parent" model. This is also in line with the OpenApi schema that would be generated.

schferbe avatar Feb 17 '22 16:02 schferbe

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 27 '22 12:04 stale[bot]

bump

schferbe avatar Apr 28 '22 14:04 schferbe

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 13 '22 23:07 stale[bot]

bump

schferbe avatar Aug 01 '22 17:08 schferbe

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Oct 01 '22 02:10 stale[bot]

Okay - I think this makes sense.(?)

Is there an example that's more obvious than a DecimalField pk? Feels pretty confusing using a Decimal as a primary key.

tomchristie avatar Oct 04 '22 11:10 tomchristie

instead o using decimal field as primary key, can you try something else like UUID field as primary key here in test case?

auvipy avatar Dec 08 '22 03:12 auvipy