Skip to content

Conversation

@felixxm
Copy link
Member

@felixxm felixxm commented Nov 28, 2025

Thanks Simon Charette for the implementation idea.

ticket-23533

@felixxm felixxm changed the title Fixed #23533 -- Allow defining initial filters on QuerySet classes. Fixed #23533 -- Allowed defining initial filters on QuerySet classes. Nov 28, 2025
Thanks Simon Charette for the implementation idea.
Copy link
Member

@charettes charettes left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still short on time today but I could swear I had a branch somewhere to approach this problem slightly differently.

By defining a class_or_instance_method like object that accumulates method calls when called on a class in a generic way you could extend this pattern to any QuerySet method easily. e.g.

class queryset_method:
    def __init__(self, method):
        self.method = method

    def buffer_call(self, cls, *args, **kwargs):
        cls._buffered_calls.append((self.method.__name__, args, kwargs))
        return cls
 
    def __get__(self, instance, owner):
        if instance is None:
            # Avoid creating intemediary types for chained calls.
            if (buffered_calls := getattr(owner, "_buffered_calls", None)) is None:
                cls = type(
                    f"Buffered{owner.__name__}",
                    (owner,),
                    {"_buffered_calls": []},
                )
            else:
                cls = owner
            return partial(self.buffer_call, cls)
        return self.method

then at queryset construction time you simply have to iterate on ._buffered_calls and apply all the method calls. Assuming you decorate filter, exclude, select_related and friend you'd be able to do

class Book(models.Model):
    ...
    published_objects = models.QuerySet.exclude(
        published_at=None,
    ).select_related("author").as_manager()

You do loose the level of immediate validation you get in your specialized class method (e.g. PROHIBITED_FILTER_KWARGS) but you still get it at queryring time just like you would get if you wrote your owner Manager.get_queryset subclass and passed invalid kwargs.

Comment on lines 1632 to 1636
return type(
class_name,
(cls,),
{"_initial_filter": initial_filter},
)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'll likely need a way to pickle these dynamically objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants