[Fixed]-Django: Filtering on the related object, removing duplicates from the result

20đź‘Ť

âś…

Adding .distinct() will give you only distinct results.

10đź‘Ť

See the QuerySet API Docs for the “distinct()” function:

Returns a new QuerySet that uses
SELECT DISTINCT in its SQL query. This
eliminates duplicate rows from the
query results.

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

👤James Polley

Leave a comment