Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a query set with the results of another query set in Django?

Right now I have a Django queryset that I want to filter by the result of another query set. Right now I am doing this as (and it works):

field = 'content_object__pk'
values = other_queryset.values_list(field, flat=True)
objects = queryset.filter(pk__in=values)

where the field is the name of a foreign key the pk in queryset. The ORM is smart enough to run the above is one query.

I was trying to simplify this to (ie to filter with the object list themselves rather than having to explicitly say pk):

field = 'content_object'
objects = queryset & other_queryset.values_list(field, flat=True)

but this gives the following error:

AssertionError: Cannot combine queries on two different base models.

What is the right way to do this type of filtering?

like image 272
Alex Rothberg Avatar asked Oct 17 '14 19:10

Alex Rothberg


People also ask

Can I filter a QuerySet Django?

With the Django QuerySet class, you can apply filters that return QuerySets defined by your filters. The filter() method returns all objects that match the keyword arguments given to the method.

How do I join a query set in Django?

You can also use the chain() method from the Itertools module, which allows you to combine two or more QuerySets from different models through concatenation. Alternatively, you can use union() to combine two or more QuerySets from different models, passing all=TRUE if you want to allow duplicates.

How do you filter QuerySets dynamically?

GET data to the UserFilter class, along with the QuerySet we want to filter. It will generate a Django Form with the search fields as well as return the filtered QuerySet. So basically we will be working inside the UserFilter definition and the HTML template, displaying properly the data.


1 Answers

You can do the next:

result = MyModel.objects.filter(field__in=other_query)

The results will be the objects in the model where the field is a foreign key to the model in the other_query

like image 120
JuanB Avatar answered Oct 19 '22 18:10

JuanB