Skip to content

Commit

Permalink
fix error with PrimaryKeyRelatedField on non-ModelSerializer #353
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Aug 25, 2022
1 parent eb0f6ab commit 42dc1c9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
10 changes: 9 additions & 1 deletion drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,9 +664,17 @@ def _map_serializer_field(self, field, direction, bypass_extensions=False):
if isinstance(field.parent, serializers.ManyRelatedField):
model = field.parent.parent.Meta.model
source = field.parent.source.split('.')
else:
elif hasattr(field.parent, 'Meta'):
model = field.parent.Meta.model
source = field.source.split('.')
else:
warn(
f'Could not derive type for under-specified PrimaryKeyRelatedField '
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.'
)
return append_meta(build_basic_type(OpenApiTypes.STR), meta)

# estimates the relating model field and jumps to it's target model PK field.
# also differentiate as source can be direct (pk) or relation field (model).
Expand Down
14 changes: 14 additions & 0 deletions tests/test_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,3 +500,17 @@ def view_func(request, format=None):
generate_schema('/x/', view_function=view_func)
stderr = capsys.readouterr().err
assert 'parameter "test"' in stderr


def test_primary_key_related_field_without_serializer_meta(capsys):
class XSerializer(serializers.Serializer):
field = serializers.PrimaryKeyRelatedField(read_only=True)

@extend_schema(responses=XSerializer, request=XSerializer)
@api_view(['GET'])
def view_func(request, format=None):
pass # pragma: no cover

generate_schema('/x/', view_function=view_func)
stderr = capsys.readouterr().err
assert 'Could not derive type for under-specified PrimaryKeyRelatedField "field"' in stderr

0 comments on commit 42dc1c9

Please sign in to comment.