9đź‘Ť
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.
4đź‘Ť
I don’t think that query can ever give duplicate results.
I just tried a similar query on my similar setup, it will convert to an SQL query which looks roughly like this:
SELECT *
FROM event
WHERE (subject=x OR object=x OR place=x)
This will not duplicate any rows, so you don’t actually need to do anything to avoid duplicate records.
- [Django]-CSRF verification failed after adding a filefield on model
- [Django]-Django application not logging request info in production log file when deployed with gunicorn and Nginx