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.
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
This will generate the
referenced_modelfield asUUIDinstead ofint. Removingreferenced_modelfromreadonly_fieldsremoves this issue. This happens, because the generator will look at the PK ofReferencingModel. The culprit is here:drf-spectacular/drf_spectacular/openapi.py
Lines 482 to 485 in f23de89
Expected behavior
A
PrimaryKeyRelatedFieldshould generate the correct type regardless of whether it is read-only or not.