Yura Bysaha
Yura Bysaha

Reputation: 779

How to do LEFT OUTER JOIN on Django ORM on non ForeignKey field

I have 2 models:

model A:
  name = CharField()
  ...

model B:
  title = CharField(null=True)
  ...

I want to get all record of model A which do not have record in model B by "name" = "title"

ON SQL I got this by:

SELECT  "A".* 
    FROM "A"
    LEFT OUTER JOIN "B"
     ON "A"."name" = "B"."title"
WHERE "B"."title" IS NULL

How to write this using Django ORM?

Upvotes: 0

Views: 52

Answers (1)

alonraiz
alonraiz

Reputation: 118

You can use a simple exclude with a subquery of all titles from model B as following:

A.objects.exclude(name__in=B.objects.all().values('title))

Upvotes: 1

Related Questions