How to use Union Method In Django

In this example, we have two QuerySets of authors from the USA and the UK. We use the union method to combine them into a single QuerySet.

Python3




from .models import Author
 
authors1 = Author.objects.filter(country='USA')
authors2 = Author.objects.filter(country='UK')
 
combined_queryset = authors1.union(authors2)


How to combine multiple QuerySets in Django?

QuerySets allow you to filter, order, and manipulate data from your database using a high-level Pythonic syntax. However, there are situations where you may need to combine multiple QuerySets into a single QuerySet to work with the data more efficiently. This article will explore various methods to achieve this in Django.

Similar Reads

What is a QuerySet in Django?

Before combining QuerySets, let’s have a quick refresher on what a QuerySet is in Django. A QuerySet is a collection of database queries to retrieve data from your database. It represents a set of records from a database table or a result of a database query. Query sets are lazy, meaning they are not evaluated until you explicitly request the data, which makes them highly efficient....

The chain function from itertools

...

Using Union Method

In this example, we first import the chain function from itertools. Then, we retrieve the QuerySets for both the Author and Book models using objects.all(). Finally, we use a chain to combine these QuerySets and convert the result into a list....

Using Q Objects Method

...

Create a project to apply combine multiple QuerySets in Django

In this example, we have two QuerySets of authors from the USA and the UK. We use the union method to combine them into a single QuerySet....

Contact Us