django-rest-framework
django-rest-framework copied to clipboard
Detect underlying field for OneToOne primary key
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.
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.
bump
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.
bump
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.
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.
instead o using decimal field as primary key, can you try something else like UUID field as primary key here in test case?