1👍
✅
You can do this with an Exists
subquery [Django-doc]:
from django.db.models import Exists, OuterRef
ModelA.objects.annotate(
has_b=Exists(ModelB.objects.filter(some_id=OuterRef('some_id'))),
has_c=Exists(ModelC.objects.filter(some_id=OuterRef('some_id')))
)
That being said, if the some_id
s of ModelB
and ModelC
always refer to a some_id
of ModelA
, then it is better to use a ForeignKey
[Django-doc] since this guarantees referential integrity, and makes it more convenient to use the ORM.
Source:stackexchange.com