Django Models Union Operation

As a developer, I’ve worked extensively with Django, the efficient web framework that makes building web applications a breeze. One common task I often encounter is combining data from different querysets, and that’s where the union operation comes into play.

If you’ve ever wanted to merge querysets from the same or even different Django models, you know it’s not always easy. Django’s ORM provides a clean way to perform these unions, but understanding how to use it effectively can save you time and make your code cleaner.

In this tutorial, I’ll walk you through how to perform union operations on Django models with real-world examples.

What is a Union Operation in Django?

Union operation in Django allows you to combine two or more querysets into a single queryset that contains all unique records from each. It’s similar to the SQL UNION statement.

This is particularly useful when you want to:

  • Merge data from two querysets of the same model.
  • Combine querysets from different models that share similar fields.
  • Avoid duplicates automatically since union returns distinct entries.

Check out File Upload in Django

Method 1: Union on Querysets from the Same Model

This is the most common scenario. Suppose you have a model Customer with data coming from two different filters, and you want to combine those results.

Example: Combine Customers from Two States

Imagine you want to get a combined list of customers from California and Texas.

from django.db import models

class Customer(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    state = models.CharField(max_length=50)
    email = models.EmailField()

# Querysets filtered by state
california_customers = Customer.objects.filter(state='California')
texas_customers = Customer.objects.filter(state='Texas')

# Perform union operation
combined_customers = california_customers.union(texas_customers)

# Iterate and print
for customer in combined_customers:
    print(customer.first_name, customer.last_name, customer.state)

What’s happening here?

  • Both querysets come from the same model (Customer).
  • .union() merges them into one queryset with unique customers.
  • This is efficient and uses Django’s ORM to generate the proper SQL behind the scenes.

You can see the output in the screenshot below.

django union

Read How to Deploy an AI Model with Django

Method 2: Union on Querysets from Different Models

Sometimes, you may want to combine data from two different models that share similar fields. For example, suppose you have two models: RetailCustomer and WholesaleCustomer both with first_name, last_name, and email.

Example: Merge Retail and Wholesale Customers

from django.db import models

class RetailCustomer(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()

class WholesaleCustomer(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()

# Querysets from different models - select only common fields
retail_qs = RetailCustomer.objects.values('first_name', 'last_name', 'email')
wholesale_qs = WholesaleCustomer.objects.values('first_name', 'last_name', 'email')

# Perform union operation
combined_customers = retail_qs.union(wholesale_qs)

# Print combined customers
for customer in combined_customers:
    print(customer['first_name'], customer['last_name'], customer['email'])

Key points:

  • Since models differ, we use .values() to select matching fields.
  • The union works on these values querysets, returning dictionaries with the specified fields.
  • This approach is great when you want to combine similar data structures without merging models.

You can see the output in the screenshot below.

django union querysets

Check out Build a Chat App in Django

Method 3: Use | Operator for Queryset Union (Same Model Only)

Django also supports the | operator to combine querysets from the same model, which is a shortcut for union.

Example:

california_customers = Customer.objects.filter(state='California')
texas_customers = Customer.objects.filter(state='Texas')

combined_customers = california_customers | texas_customers

for customer in combined_customers.distinct():
    print(customer.first_name, customer.last_name, customer.state)

Note:

  • Unlike .union(), the | operator returns a queryset that may contain duplicates unless you call .distinct().
  • Use this method for quick unions on the same model.

Important Tips When Using Union in Django

  • Ordering: Django doesn’t allow ordering before a union operation. You should apply .order_by() after the union.
  • Fields must match: When unioning querysets, the fields and their order must be the same.
  • Distinct results: .union() always returns distinct results; duplicates are removed automatically.
  • Performance: Union queries are executed on the database side, which is efficient for large datasets.

Read Compare Two Integers in Python Django

Real-World Use Case: Combine Event Attendees from Multiple Sources

Suppose you are managing an event app in the USA and have two models: OnlineAttendee and OfflineAttendee. You want to get a combined list of all attendees, regardless of how they registered.

class OnlineAttendee(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()

class OfflineAttendee(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()

online_attendees = OnlineAttendee.objects.values('first_name', 'last_name', 'email')
offline_attendees = OfflineAttendee.objects.values('first_name', 'last_name', 'email')

all_attendees = online_attendees.union(offline_attendees).order_by('last_name')

for attendee in all_attendees:
    print(f"{attendee['first_name']} {attendee['last_name']} - {attendee['email']}")

This approach lets you efficiently combine attendees from different registration methods into one list.

Performing union operations on Django models is easy once you understand the nuances. Whether you’re merging data from the same model or combining fields from different models, Django’s ORM has you covered with clean and efficient methods.

Try these techniques in your next Django project, and you’ll find managing combined datasets much easier!

You may also read other Django-related tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.