18👍
✅
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.
Source:stackexchange.com