Skip to content

ModelSerializer default querysets #5358

@bobort

Description

@bobort

Some of my ForeignKeys in my models use the limit_choices_to argument. I was a bit surprised to find that the auto-generated forms did not follow the same rules, so I find myself overriding the queryset argument used in my custom ModelSerializer class.

I've never contributed source code to a project, and I really don't know how to do it, but I would like to propose the following replacement to rest_framework/relations.py, line 158:

            if hasattr(self.parent, "Meta") and hasattr(self.parent.Meta, "model"):
                queryset = queryset.filter(
                    **self.parent.Meta.model._meta.get_field(self.source).get_limit_choices_to()
                )
            else:
                queryset = queryset.all()

Truth be told, there's a comment in there about repr output, and my worthless opinion is that you have an incredibly bizarre reason to pass around Managers from the ModelSerializer instead of QuerySets. Isn't there a way to obtain the manager from a QuerySet object so that you can create your own custom repr for them if they're really that important for everyone? But, I digress...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions