Combine 2 Django Querysets from Different Models

If you’ve ever tried to concatenating two or more querysets from different models (i.e. combined = queryset1 | queryset2), you’ve hit this lovely error:

Cannot combine queries on two different base models.

The solution to this is to use itertools.

from itertools import chain
result_list = list(chain(queryset1, queryset2))

view raw
query.py
hosted with ❤ by GitHub

This allows you to not only combine the querysets into a single iterable, but it also allows you to sort the entire set by a shared field such as the date created:

from itertools import chain
from operator import attrgetter
# ascending oreder
result_list = sorted(
chain(queryset1, queryset2),
key=attrgetter('date_created'))
# descending order
result_list = sorted(
chain(queryset1, queryset2),
key=attrgetter('date_created'),
reverse=True)

view raw
query.py
hosted with ❤ by GitHub

9 thoughts on “Combine 2 Django Querysets from Different Models”

  1. How would the front end code look to display the required fields from all the chained models in the front end templates?

      1. Is there a generic CBV that could handle these chained querySets? Can’t figure out how to unwrap these things.

  2. hello man! I used chain to combine two different query set, but the problem I am having is that I can not sort or filter using the slug. it seems chain does not allow .object.get(slug)

    def sport_list(request, slug):
    travels= Travel.objects.all().order_by(‘-date’)
    nutritions= Nutrition.objects.all().order_by(‘-date’)
    sports= Sport.objects.all().order_by(‘-date’)

    sportas = chain(travels, nutritions, sports)
    newone = sportas.object.get(slug)

Leave a Reply to Chris Kief Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s