Skip to content

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

@diesieben07

Description

@diesieben07

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions