Skip to main content
 首页 » 编程设计

python之Q 对象的不同值

2025年05月04日14haluo1

我在 Py3 上的 Django 项目 1.10.1 上有这个查询:

Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id)) 

如何防止获得两个相同的 Event 记录?

提前谢谢你。

请您参考如下方法:

使用 distinct运算符(operator):

Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id)).distinct() 

来自文档:

By default, a QuerySet will not eliminate duplicate rows. In practice, this is rarely a problem, because simple queries such as Blog.objects.all() don’t introduce the possibility of duplicate result rows. However, if your query spans multiple tables, it’s possible to get duplicate results when a QuerySet is evaluated. That’s when you’d use distinct().

在实现之前特别注意他们的“However”子句,除非您希望实际看到重复的结果。