'django annotate whether exists or not

I have a query I'm using:

people = Person.objects.all().annotate(num_pets=Count('pets'))
for p in people:
    print(p.name, p.num_pets == 0)

(Pet is ManyToOne with Person)

But i'm actually not interested in the number of pets, but only on whether a person has any pets or not. How can this be done?



Solution 1:[1]

You can make use of an Exists expression [Django-doc] to determine if there exists a Pet for that Person. For example:

from django.db.models import Exists, OuterRef

Person.objects.annotate(
    has_pet=Exists(Pet.objects.filter(person=OuterRef('pk')))
)

Here the model is thus Pet that has a ForeignKey named person to Person. If the fields are named differently, then you should of course update the query accordingly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1