Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct values with Q objects

Tags:

python

django

I have this query on my Django project 1.10.1 on Python 3:

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

How can I prevent to get two identical Event records?

like image 685
Giacomo Sarrocco Avatar asked Nov 01 '25 00:11

Giacomo Sarrocco


1 Answers

Use the distinct operator:

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

From the documentation:

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().

Make special note of their "However" clause before implementing this unless you expect to actually see duplicate results.

like image 195
enderland Avatar answered Nov 03 '25 14:11

enderland