32👍
How about something along these lines:
Thing.objects.filter(field__in=Another_Thing.object.filter())
Django will do query and subquery.
1👍
Many year after I found a solution.
You can use the __dict__
prop from you queryset. For instance:
o = Model.objects.filter(arg=param)
o2 = Model.objects.all()
o2.query.__dict__ = o.query.__dict__
o2.filter(arg2=param2)
o2 will now is filtered by arg and arg2!
I used this to pass a ModelChoiceField filter to django-jet autocomplete views (fork at https://github.com/paulorsbrito/django-jet).
Hope this helps someone in trouble.
0👍
As far as I can tell from looking through the QuerySet and Query modules, Django doesn’t keep a running record of the arguments you send into a queryset. It translates everything directly into lower level query fragments then discards the tokens you’ve given it. Thus, figuring out how a queryset has been filtered without prior knowledge is a non-trivial task.
You could do it manually by hacking together something like the following:
q0 = Thing.objects.all()
filter_kwargs = {'x': y}
fq0 = q0.filter(**filter_kwargs)
fq0.saved_filter_kwargs = filter_kwargs
##### snip #####
fq1 = q1.filter(**fq0.saved_kwargs)
Kind of nasty though. Probably better to try solving this problem in a different way. I’d recommend you post another question and include what you’re trying to achieve in the big picture, and we might be able to help you come up with a better architecture.