如何找到两个 Django 查询集的并集?
我有一个带有两个自定义管理器方法的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这有效并且看起来更干净:
如果您不想重复,那么您将需要附加
.distinct()
:This works and looks a bit cleaner:
If you don't want duplicates, then you will need to append
.distinct()
:从版本1.11开始,django查询集有一个内置的union方法。
有关更多示例,请参阅我的博客文章。
Starting from version 1.11, django querysets have a builtin union method.
See my blog post on this for more examples.
我建议使用 'query1.union(query2)' 而不是 'query1 |查询2';
我从上述两种方法得到了不同的结果,前一种方法是我所期望的。
以下是我遇到的
结果:
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:
result:
组合or操作时,就像这个例子:
ab结果包含很多结果。可以调用 distinct() 但即使我执行它也会尝试太多时间来执行
When combining or operations, like in this example:
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