On Sun, 1 Jan 2023 16:33:45 +0200
Ramez Ashraf <
ramez...@gmail.com> wrote:
>
> Interested or do you think the function can be enhanced it to make
> more useable for your everyday other cases ?
>
This is half-baked, just a thought, but maybe you can take it some
place interesting:
Imagine a class that "collects" calls for later execution. Something
like (this exactly won't work, details below):
from functools import partialmethod
from django.db.models import QuerySet as QSet
class QS:
def __init__(self):
self._calls = []
def filter(self, *args, **kw):
self._calls.append(
partialmethod(QSet.filter, *args, **kw)
)
return self
def annotate(*args, **kw):
# ... (same idea)
# ... other relevant methods,
def __call__(self, qset):
for call in self._calls:
qset = apply(call, qset)
return qset
This won't work, I think, because partialmethod isn't supposed to work
quite this way, and the "apply" in the last line isn't defined. But
with this (fixed) already you could, I think, do something like
def qset_manager(qs: QS) -> Manager
class CustomManager(models.Manager):
def get_queryset(self):
orig = super().get_queryset()
return qs(orig)
return CustomManager()
And then, in your model,
class Person(models.Model):
...
authors = qset_manager(QS().filter(role="A"))
and now the "make a manager with a modified queryset" pattern is
shortened in a general way.
As I said, just a half-baked thought. There's problems here to solve,
and many improvements to make.
HTH,
Shai.