'Is there any way to make a manual join using Django ORM?

lets say I have the following models:

class ModelA(models.Model):
    pass

class ModelB(ModelA):
    pass

class ModelC(models.Model):
    model_a = models.ForeignKey(ModelA)

class ModelD(models.Model):
    model_c = models.ForeingKey(ModelC)

And I need to filter all the instances of ModelD that have a relation in ModelB. Is there any way to remove the unnecesary joins in the query that the queryset will produce ?

ModelD.objects.filter(model_c__model_a__model_b__id__isnull=False)

If there's any way to make a filter like this:

ModelD.objects.filter(model_c__model_b__id__isnull=False)

I know how to make the query on SQL, but for terms of readabilty and code maintenance I would like to know if there's any way to make the manual join or to remove that intermediate join.

Thanks in advance for the replies !

Edit: I want to use the field that the inheritance of ModelA in ModelB generates, the one that's called app_modelb.modela_ptr_id in the database



Solution 1:[1]

For this to be true, you should have a field model_b that is foreign-key to ModelB in the model ModelC. That is how the query works in Django (or any other framework that plays with databases).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ajay_110125