This can be done using union
. After doing this, the type of the result can be seen as <class 'django.db.models.query.QuerySet'>
. So two querysets can be combined. Lets see an example.
query1 = User.objects.filter(is_active=True)
query2 = User.objects.filter(is_active=False)
combined_query = query1.union(query2)
print (type(combined_query))
The above program will print result as below, confirming it is a queryset
<class 'django.db.models.query.QuerySet'>
So basically Django executes the below query for union.
(SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."is_active" = True)
UNION
(SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."is_active" = False)
This also means that there will be error(django.db.utils.ProgrammingError: each UNION query must have the same number of columns
) if union is tried with two different tables.