Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a django QuerySet with the query from another QuerySet: Possible?

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.

like image 562
dmr parthenon Avatar asked Dec 02 '11 03:12

dmr parthenon


People also ask

Can I filter a Queryset Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What does Queryset filter return?

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.

How do I merge two QuerySets in Django?

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.

Which can be used to retrieve an object directly instead of a Queryset?

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.


2 Answers

How about something along these lines:

Thing.objects.filter(field__in=Another_Thing.object.filter())

Django will do query and subquery.

like image 81
zzart Avatar answered Oct 09 '22 21:10

zzart


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.

like image 25
Paulo Brito Avatar answered Oct 09 '22 21:10

Paulo Brito