How to combine multiple QuerySets in Django with code example?

In Django, you can combine multiple QuerySets using the union() method to create a new QuerySet that contains the combined results of the original QuerySets. Here’s how you can do it with a code example:

Let’s assume you have a model named Book and you want to combine QuerySets of books based on different criteria, such as books published in the last year and books with a certain author’s name. Here’s how you can use the union() method:

from datetime import datetime, timedelta
from django.db.models import Q
from .models import Book

# QuerySet for books published in the last year
last_year_books = Book.objects.filter(pub_date__gte=datetime.now() - timedelta(days=365))

# QuerySet for books by a specific author
specific_author_books = Book.objects.filter(author='J.K. Rowling')

# Combine the QuerySets using union()
combined_books = last_year_books.union(specific_author_books)

# Iterate through the combined QuerySet
for book in combined_books:
print(book.title, book.author, book.pub_date)

In this example, we first create two separate QuerySets: last_year_books for books published in the last year and specific_author_books for books by a specific author. Then, we use the union() method to combine these two QuerySets into a single QuerySet named combined_books.

Keep in mind the following points when using union():

  • The union() method requires both QuerySets to have the same fields and types.
  • union() performs deduplication by default, so if there are duplicate records, they will be removed. If you want to keep duplicates, you can use the all=True argument: combined_books = last_year_books.union(specific_author_books, all=True).

Remember that union() works on QuerySets and may not be supported by all database backends in Django. If union() is not supported by your database, you might need to use other methods to achieve similar results, such as converting QuerySets to lists and combining them using Python’s list operations.