Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django annotate whether exists or not

Tags:

python

sql

django

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?

like image 981
user972014 Avatar asked Dec 30 '25 14:12

user972014


1 Answers

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.

like image 85
Willem Van Onsem Avatar answered Jan 01 '26 05:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!