user695652
user695652

Reputation: 4275

Django: Get objects for which ForeignKey does not exist

Given:

class A(models.Model):
   ...

class B(models.Model):
   ...

class C(models.Model):
    a  = models.ForeignKey(A)
    b  = models.ForeignKey(B)

For a fixed b of class B, I would like to retrieve all those Objects a from A, for which there is no entry (a,b) in C.

I am failing to come up with a correct filter to achieve this.

Upvotes: 2

Views: 788

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

Start with class A, since that's the type of object you ultimately want. You'll either want to filter those or exclude them. We could try to filter for the objects that don't have a matching entry, but you know what? It'll be easier to exclude the ones that do have a match.

Assuming class A has a related field of c for the C.a foreign key...

A.objects.exclude(c__b=b)

Upvotes: 3

Related Questions