Reputation: 2560
I have two models:
ModelA:
id = models.AutoField(primary_key=True)
ModelB:
id = models.AutoField(primary_key=True)
titlecomponent = models.ForeignKey('ModelA',on_delete=models.PROTECT)
How can i get all objects of ModelA which have not any record relationsip in ModelB.
Upvotes: 1
Views: 425
Reputation: 476709
You can do that by comparing with None
:
ModelA.objects.filter(modelb=None)
The reason this works is because a LEFT OUTER JOIN
is performed, and thus if no related ModelB
exists, then a row that contains NULL
s is added.
This will thus boil down to a query that looks like:
SELECT app_modela.*
FROM app_modela
LEFT OUTER JOIN app_modelb ON app_modelb.titlecomponent = app.modela.id
WHERE app_modelb.id IS NULL
Upvotes: 3