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.

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:

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

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

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s