Skip to content

Subclassed PrimaryKeyRelatedField.get_queryset alongside with Serializer fails generating schema #1471

@SafaAlfulaij

Description

@SafaAlfulaij

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)

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions