Giacomo Sarrocco Giacomo Sarrocco - 1 year ago 112
Python Question

Distinct values with Q objects

I have this query on my Django project 1.10.1 on Py3:

Event.objects.filter(Q( | Q( | Q(

How can I prevent to get two identical

Thank you in advance.

Answer Source

Use the distinct operator:

Event.objects.filter(Q( | Q( | Q(

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download