0
0
DjangoHow-ToBeginner · 3 min read

How to Use Union in Django QuerySet: Syntax and Examples

In Django, you can combine two or more QuerySets using the union() method to get a single QuerySet with unique results from all. The QuerySets must be from the same model or have compatible fields, and you can chain union() calls to combine multiple QuerySets.
📐

Syntax

The union() method combines two or more QuerySets into one, returning unique records from all. The basic syntax is:

  • qs1.union(qs2, qs3, all=False)

Where:

  • qs1, qs2, qs3 are QuerySets to combine.
  • all=False means duplicate rows are removed (default).
  • All QuerySets must have the same fields in the same order.
python
combined_qs = qs1.union(qs2, qs3, all=False)
💻

Example

This example shows how to combine two QuerySets from the same model using union(). It fetches users from two different filters and merges them without duplicates.

python
from django.contrib.auth.models import User

# QuerySet 1: Users with first name starting with 'A'
qs1 = User.objects.filter(first_name__startswith='A').values('id', 'username')

# QuerySet 2: Users with last name starting with 'B'
qs2 = User.objects.filter(last_name__startswith='B').values('id', 'username')

# Combine QuerySets using union
combined_qs = qs1.union(qs2)

# Print usernames from combined QuerySet
for user in combined_qs:
    print(user['username'])
Output
alice alex bob brian
⚠️

Common Pitfalls

Common mistakes when using union() include:

  • Using QuerySets with different fields or field orders causes errors.
  • Forgetting to use .values() or .values_list() when combining QuerySets from different models or with different fields.
  • Assuming union() preserves order; it does not guarantee order.
  • Not using all=True if you want to keep duplicates.

Example of wrong and right usage:

python
# Wrong: Different fields
qs1 = User.objects.values('id', 'username')
qs2 = User.objects.values('id', 'email')

# This will raise an error:
# combined = qs1.union(qs2)

# Right: Same fields and order
qs1 = User.objects.values('id', 'username')
qs2 = User.objects.filter(is_staff=True).values('id', 'username')
combined = qs1.union(qs2)
📊

Quick Reference

MethodDescription
union(qs1, qs2, all=False)Combine QuerySets with unique results (default)
union(qs1, qs2, all=True)Combine QuerySets including duplicates
.values('field1', 'field2')Select specific fields to ensure compatibility
QuerySets must have same fields and orderAvoid errors by matching fields exactly
Ordering is not guaranteedUse .order_by() after union if needed

Key Takeaways

Use union() to combine QuerySets with matching fields and get unique results by default.
Ensure all QuerySets have the same fields in the same order, often using .values().
Set all=True if you want to include duplicates in the combined QuerySet.
Ordering is not preserved after union; apply .order_by() if order matters.
Avoid mixing QuerySets with different fields to prevent errors.