Skip to content

Commit

Permalink
Merge pull request #1338 from tfranzel/pk_field
Browse files Browse the repository at this point in the history
consider pk_field on PrimaryKeyRelatedField when set #1335
  • Loading branch information
tfranzel authored Nov 27, 2024
2 parents 3b778f0 + cc5a5d1 commit 304a61f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
7 changes: 5 additions & 2 deletions drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,7 +699,10 @@ def _map_serializer_field(self, field, direction, bypass_extensions=False):
# read_only fields do not have a Manager by design. go around and get field
# from parent. also avoid calling Manager. __bool__ as it might be customized
# to hit the database.
if getattr(field, 'queryset', None) is not None:
if not is_slug and getattr(field, 'pk_field') is not None:
schema = self._map_serializer_field(field.pk_field, direction)
return append_meta(schema, meta)
elif getattr(field, 'queryset', None) is not None:
if is_slug:
model = field.queryset.model
source = [field.slug_field]
Expand All @@ -718,7 +721,7 @@ def _map_serializer_field(self, field, direction, bypass_extensions=False):
f'Could not derive type for under-specified {field.__class__.__name__} '
f'"{field.field_name}". The serializer has no associated model (Meta class) '
f'and this particular field has no type without a model association. Consider '
f'changing the field or adding a Meta class. defaulting to string.'
f'changing the field or adding a Meta class. Defaulting to string.'
)
return append_meta(build_basic_type(OpenApiTypes.STR), meta)

Expand Down
17 changes: 17 additions & 0 deletions tests/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3444,3 +3444,20 @@ class XViewset(viewsets.ModelViewSet):
'readOnly': True
}
}


def test_primary_key_related_field_with_custom_pk_field(no_warnings):
class XSerializer(serializers.Serializer):
field = serializers.PrimaryKeyRelatedField(
read_only=True,
pk_field=serializers.IntegerField(),
)

class XViewset(viewsets.ModelViewSet):
serializer_class = XSerializer
queryset = SimpleModel.objects.all()

schema = generate_schema('/x', XViewset)
assert schema['components']['schemas']['X']['properties']['field'] == {
'readOnly': True, 'type': 'integer'
}

0 comments on commit 304a61f

Please sign in to comment.