-
Notifications
You must be signed in to change notification settings - Fork 307
Open
Description
Describe the bug
Using a subclassed serializers.PrimaryKeyRelatedField with get_queryset to validate incoming payloads with a Serializer fails generating schema.
To Reproduce
from rest_framework import serializers
from django.contrib.auth.models import User
class UserRelatedField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
return User.objects.all()
class TestSerializer(serializers.Serializer):
user_ids = UserRelatedField(many=True)
- Error message:
'TestSerializer' object has no attribute 'Meta' - Error line: https://github.com/SafaAlfulaij/drf-spectacular/blob/02971bd89e25e0a3cda5f94400ab497f20112f7d/drf_spectacular/openapi.py#L717
- Error reason: we are assuming that
PrimaryKeyRelatedFieldare only used inModelSerializerobjects, which defines aMetasub class.PrimaryKeyRelatedFieldcan be used in normalSerializerinstances.
Expected behavior
Schema generates normally respecting get_queryset.
Others
Using queryset directly in the field (instead of subclassing) works normally.
Subclassing with a get_queryset causes the issue.
Possible Solution
Handling get_queryset solves the issue. I failed to update the test cases, hence didn't open a PR:
elif queryset := field.get_queryset() and isinstance(queryset, (Queryset, Manager)):
if is_slug:
model = queryset.model
source = [field.slug_field]
model_field = follow_field_source(model, source, default=models.TextField())
else:
model_field = queryset.model._meta.pk
(We do the check to avoid catching read-only cases.)
Metadata
Metadata
Assignees
Labels
No labels