Detect underlying field for OneToOne primary key

This commit is contained in:
Benjamin Schäfer 2022-02-17 16:51:01 +01:00
parent efc7c1d664
commit 1129a8dacd
2 changed files with 22 additions and 0 deletions

View File

@ -1234,6 +1234,10 @@ class ModelSerializer(Serializer):
if model_field.one_to_one and model_field.primary_key:
field_class = self.serializer_related_field
field_kwargs['queryset'] = model_field.related_model.objects
pk_field = field_mapping[model_field.foreign_related_fields[0]]
pk_field_kwargs = get_field_kwargs(field_name, model_field.foreign_related_fields[0])
pk_field_kwargs.pop("model_field")
field_kwargs["pk_field"] = pk_field(**pk_field_kwargs)
if 'choices' in field_kwargs:
# Fields with choices get coerced into `ChoiceField`

View File

@ -762,3 +762,21 @@ class Test8301Regression:
assert (s.data | {}).__class__ == s.data.__class__
assert ({} | s.data).__class__ == s.data.__class__
class TestRelatedFieldTypes:
def test_one_to_one_field(self):
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 MyModelBSerializer(serializers.ModelSerializer):
class Meta:
model = MyModelB
fields = "__all__"
ser = MyModelBSerializer()
assert type(ser.fields["id"].pk_field) == fields.DecimalField