这可以使用union 来完成。这样做之后,结果的类型可以看到为<class 'django.db.models.query.QuerySet'>。因此可以组合两个查询集。让我们看一个例子。
query1 = User.objects.filter(is_active=True)
query2 = User.objects.filter(is_active=False)
combined_query = query1.union(query2)
print (type(combined_query))
上面的程序将打印如下结果,确认它是一个查询集
<class 'django.db.models.query.QuerySet'>
所以基本上 Django 执行以下联合查询。
(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)
这也意味着如果对两个不同的表尝试联合,将会出现错误(django.db.utils.ProgrammingError: each UNION query must have the same number of columns)。