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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With