如何找到两个 Django 查询集的并集?

发布于 2024-10-06 17:25:53 字数 106 浏览 0 评论 0原文

我有一个带有两个自定义管理器方法的 Django 模型。每个都根据对象的不同属性返回模型对象的不同子集。

有没有办法获取查询集,或者只是对象列表,即每个管理器方法返回的查询集的并集?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

昵称有卵用 2024-10-13 17:25:53

这有效并且看起来更干净:

records = query1 | query2

如果您不想重复,那么您将需要附加 .distinct()

records = (query1 | query2).distinct()

This works and looks a bit cleaner:

records = query1 | query2

If you don't want duplicates, then you will need to append .distinct():

records = (query1 | query2).distinct()
殊姿 2024-10-13 17:25:53

版本1.11开始,django查询集有一个内置的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

有关更多示例,请参阅我的博客文章

Starting from version 1.11, django querysets have a builtin union method.

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 post on this for more examples.

流绪微梦 2024-10-13 17:25:53

我建议使用 '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

结果:

union result:
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object
KafkaTopic object

| result:
KafkaTopic object
KafkaTopic object

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:

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
始于初秋 2024-10-13 17:25:53

组合or操作时,就像这个例子:

a = a1 | a2
ab = a | b

ab结果包含很多结果。可以调用 distinct() 但即使我执行它也会尝试太多时间来执行

ab = a.distinct() | b.distinct()

When combining or operations, like in this example:

a = a1 | a2
ab = a | b

the ab result contains a lot of results. distinct() can be called but it tries too much time to be executed even if I exec

ab = a.distinct() | b.distinct()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文