-
-
Notifications
You must be signed in to change notification settings - Fork 33.3k
Fixed #23533 -- Allowed defining initial filters on QuerySet classes. #20336
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Thanks Simon Charette for the implementation idea.
There was a problem hiding this 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.methodthen 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.
| return type( | ||
| class_name, | ||
| (cls,), | ||
| {"_initial_filter": initial_filter}, | ||
| ) |
There was a problem hiding this comment.
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.
Thanks Simon Charette for the implementation idea.
ticket-23533