Django merging two QuerySet using itertools.

I was working with a django application where I need to merge two query set. After going through django ORM docs, could not find anything helpful.

I was planning to do it in a unpythonic way like iterating two queryset and appending each item to a new list, just before doing it I thought it would be better to google for it. And after couple of minutes found it. We can use python itertools to merge two or more query set. Like below:

from itertools import chain
cars = Cars.objects.all()
trucks = Truck.objects.all()
all_vechiles = list(chain(cars, trucks))

Python itertools is an amazing module that contains real handy methods what we need to handle iterators and doing different types of operation. If you never used  itertools before you are missing one of the charm of python.

Check Itertools chain docs for details.

Happy Coding!


  1. SutoCom · August 20, 2013
  2. DS · February 2, 2014

    This is awesome! So is itertools just built in then? Or is there some kind of itertools package I’d need to install first?

    • mushfiq · February 2, 2014

      You don’t have to install it, it is a python native module.

  3. Mike · November 18, 2014

    I tried this but you end up with a list and not a queryset so it won’t work with TastyPie. Any ideas how to get a queryset and not a list?

  4. Mike · November 18, 2014

    Haha – as soon as I post I learn that you can do:

    result = qset1 | qset2


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 )

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.