Skip to content

Detect underlying field for OneToOne primary key #8371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1234,6 +1234,10 @@ def build_standard_field(self, field_name, model_field):
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])
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the field_name be extracted from the foreign_related_fields[0] here?

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`
Expand Down
18 changes: 18 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -762,3 +762,21 @@ class TestSerializer(serializers.Serializer):

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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

decimal field as primary key? what are some actual use case of that?


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