Python 如何找到两个 Django 查询集的联合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4411049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find the union of two Django querysets?
提问by Paul D. Waite
I've got a Django model with two custom manager methods. Each returns a different subset of the model's objects, based on a different property of the object.
我有一个带有两个自定义管理器方法的 Django 模型。每个都根据对象的不同属性返回模型对象的不同子集。
Is there any way to get a queryset, or just a list of objects, that's the union of the querysets returned by each manager method?
有没有办法获得一个查询集,或者只是一个对象列表,这是每个管理器方法返回的查询集的联合?
采纳答案by Jordan Reiter
This works and looks a bit cleaner:
这有效并且看起来更干净:
records = query1 | query2
If you don't want duplicates, then you will need to append .distinct():
如果您不想重复,则需要附加.distinct():
records = (query1 | query2).distinct()
回答by Jose Cherian
Starting from version 1.11, django querysets have a builtin union method.
从version 1.11开始,django querysets 有一个内置的 union 方法。
q = q1.union(q2) #q will contain all unique records of q1 + q2
q = q1.union(q2, all=True) #q will contain all records of q1 + q2 including duplicates
q = q1.union(q2,q3) # more than 2 queryset union
See my blog poston this for more examples.
有关更多示例,请参阅我的博客文章。
回答by Xianxing
I would suggest using 'query1.union(query2)' instead of 'query1 | query2'; I got different results from the above two methods and the former one is what I expected. The following is what I had come across:
我建议使用 'query1.union(query2)' 而不是 'query1 | 查询2'; 我从上面两种方法得到了不同的结果,前一种是我所期望的。以下是我遇到的:
print "union result:"
for element in query_set1.union(query_set2):
print element
print "| result:"
for element in (query_set1 | query_set2):
print element
result:
结果:
union result:
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object
| result:
KafkaTopic object
KafkaTopic object

