Distinct values with Q objects
<p>I have this query on my Django project 1.10.1 on Py3:</p>

<pre><code>Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id))
</code></pre>

<p>How can I prevent to get two identical <code>Event</code> records? </p>

<p>Thank you in advance.</p>

<p>Use the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.distinct" rel="nofollow">distinct</a> operator:</p>

<pre><code>Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id)).distinct()
</code></pre>

<p>From the documentation:</p>

<blockquote>
  <p>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().</p>
</blockquote>

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

python django