[Solved]-Filter queryset by reverse exists check in Django


According to the documentation:

To refer to a “reverse” relationship, just use the lowercase name of the model.

From this answer it follows your code would be:

if user:
    qs = qs.filter(user=user)
if active:
    qs = qs.filter(active=active)
if has_comments:
    qs = qs.filter(comment__isnull=False)

With regards to performance take this answer into account:

Django doesn’t support the select_related() method for reverse foreign
key lookups, so the best you can do without leaving Python is two
database queries.

You should also have a look at prefetch_related which can, unlike select_related do lookups across reverse ForeignKeys, albeit with a separate query for each element of the queryset.


The query you want is:


__isnull=False on a reverse relationship allows you to filter the join for rows where a post_comment is present. However, this will give you duplicate results for each post_comment, so you need .distinct() to dedupe.


Leave a comment