Alex Rothberg
Alex Rothberg

Reputation: 10993

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

Right now I have a Django QuerySet that I want to filter by the result of another QuerySet. Right now I am doing this like so (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 as 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?

Upvotes: 10

Views: 8745

Answers (2)

JuanB
JuanB

Reputation: 180

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

Upvotes: 12

michaelwayman
michaelwayman

Reputation: 196

you can chain queries in Django...

qs = entry.objects.filter(...).filter(...)

Upvotes: -3

Related Questions