Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get objects not referenced by foreign key

Tags:

I have two models like this:

class AA(models.Model):     name = models.CharField()     state = models.IngerField()   class BB(models.Model):     aa_id = models.ForeignKey(AA) 

My question is: How i get all objects AA with state 10 and that are not in BB?

In sql i do something like this:

select * from AA  where  AA.state = 10 and AA.id not in (select aa_id from BB) 

or

select * from AA left join BB on BB.aa_id = AA.id where AA.state = 10 and BB.id is null 

I know that i can get all AA objects and check one by one if BB has foreign key to it. But is not the right thing to do.

Thanks.

like image 575
balsagoth Avatar asked Jan 21 '11 11:01

balsagoth


1 Answers

Something like this:

AA.objects.filter(state=10, bb=None) 
like image 119
Daniel Roseman Avatar answered Oct 19 '22 15:10

Daniel Roseman