[Django]-Filter Django objects where related object exists

89👍

how about …

Photo.objects.filter(complaint__isnull=False)

from https://docs.djangoproject.com/en/dev/topics/db/queries/

23👍

I’m not sure which variant is the best, but that works as well.

Photo.objects.exclude(complaint=None)

Generated SQL query is not exactly like in the case of .filter(complaint__isnull=False), but sense is identical.

0👍

Depending on the complexity of the relationship and filter logic you might need this (or this can turn out to be more readable):

complaints = Complaint.objects.filter(
    # some complex filter here
   Q(...) & Q(...) | Q(...)
)

Photo.objects.annotate(
    has_complaints=Exists(complaints)
).filter(has_complaints=True)
👤Marcos

Leave a comment