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

consider pk_field on PrimaryKeyRelatedField when set #1335 #1338

Merged
merged 1 commit into from
Nov 27, 2024
Merged
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
7 changes: 5 additions & 2 deletions drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,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 @@ -714,7 +717,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'
}
Loading