How to find the union of two query sets (QuerySet) in django?

created at 07-17-2021 views: 1

I have a Django model with two custom manager methods. Each object will be based on different attributes of the object

Return different subsets of model objects.

Is there any way to get a query set, or just a list of objects, that is the union of the query sets returned by each manager method?

The solution code is as follows:

q1 = User.objects.filter(id__gte=5)

q2 = User.objects.filter(id__lte=9)

records = q1| q2

If you don’t want to have duplicate data, you need to add a method: distinct()

records = (q1| q2).distinct()

Django version supports union method after 1.11

q = query1.union(query2) # q will contain all unique records of query1 + query2
q = query1.union(query2, all=True) # q will contain all records of query1 + query2 (including duplicate data)
q = query1.union(query2,query3) # Union of multiple sets

Merging operations between different models:

q3 = EventVillain.objects.all()


This kind of merge may encounter errors, because two different models are merged, they must have the same field or the same subset of fields. Such as:

    "name", "gender").union(Villain.objects.all().values_list(
    "name", "gender"))

This is to provide names and genders for all Hreo and Villain

Please log in to leave a comment.