user1292656
user1292656

Reputation: 2560

Filter objects if one to many relationship not exists

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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 NULLs 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

Related Questions