[Django]-Django filter() on field of related model

24đź‘Ť

âś…

It turns out there are two parts to this. First is the distinct() method, for which the doc says:

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

The following outputs “2” as expected:

len(Collection.objects.filter(item__flag=True).distinct())

However, this doesn’t help with the more complex example I gave, using annotate(). It turns out this is an instance of a known issue: https://code.djangoproject.com/ticket/10060.

👤Tom

Leave a comment