Say I create a QuerySet like:
q0 = Thing.objects.all()
fq0 = q0.filter(x=y)
at time t0. Then I add some new things to Thing db. These things form the QuerySet:
q1 = Thing.objects.filter(created_gt=t0)
I want to generate the QuerySet:
fq = (q0 | q1).filter(x=y)
Without having to know what x or y are. In other words, i'd like to be able to do something like this:
fq1 = q1.filter(query=fq0.query)
fq = fq0 | fq1
Is this possible? Manually setting
q1.query = fq0.query
merely sets q1 == fq0
. I've seen some people asking about extracting the sql from a queryset, but this won't really help me.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
filter() Returns a new QuerySet containing objects that match the given lookup parameters. The lookup parameters ( **kwargs ) should be in the format described in Field lookups below. Multiple parameters are joined via AND in the underlying SQL statement.
Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.
Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.
How about something along these lines:
Thing.objects.filter(field__in=Another_Thing.object.filter())
Django will do query and subquery.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With