Skip to content
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

PrimaryKeyRelatedFields produce incorrect schema if they are read-only #274

Closed
diesieben07 opened this issue Jan 28, 2021 · 0 comments
Closed

Comments

@diesieben07
Copy link
Contributor

diesieben07 commented Jan 28, 2021

Describe the bug
PrimaryKeyRelatedFields that are read-only are not handled correctly. When getting the model field the generator will look at the primary key of the model containing the foreign key instead of the target of the foreign key.

To Reproduce

class ReferencedModel(models.Model):
    id = models.AutoField(primary_key=True)

class ReferencingModel(models.Model):
   id = models.UUIDField(primary_key=True)
   referenced_model = models.ForeignKey(ReferencedModel, on_delete=models.CASCADE)

class ReferencingModelSerializer(serializers.Serializer):
    fields = ['id', 'referenced_model']
    read_only_fields = ['referenced_model']

This will generate the referenced_model field as UUID instead of int. Removing referenced_model from readonly_fields removes this issue. This happens, because the generator will look at the PK of ReferencingModel. The culprit is here:

if isinstance(field.parent, serializers.ManyRelatedField):
model_field = field.parent.parent.Meta.model._meta.pk
else:
model_field = field.parent.Meta.model._meta.pk
. This code is incorrect, it must instead find the ForeignKey field and then grab the targeted model from there.

Expected behavior
A PrimaryKeyRelatedField should generate the correct type regardless of whether it is read-only or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants