[Answered ]-Join onto other table where there is no foreignkey relationship

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_ids 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.

Leave a comment