Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - get all objects in one table which do not have a foreignkey in another table

I have 2 models:

class Friend(models.Model):
    person1 = models.ForeignKey("Person", related_name="friend1")
    person2 = models.ForeignKey("Person", related_name="friend2")
    created = models.DateTimeField(auto_now=True, auto_now_add=True, editable=False)

class Person(models.Model):
    firstname = models.CharField(max_length=100)
    surname = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now=True, auto_now_add=True, editable=False)

I want a list of Person objects which do not have any entries in the Friend object. e.g.

no_friends = Person.objects.filter(????)

but I'm not sure what the filter should be.

like image 819
John Avatar asked Jan 24 '11 09:01

John


1 Answers

Try to use the related manager.

no_friends = Person.objects.filter(friend1=None,friend2=None)
like image 85
Arseny Avatar answered Oct 05 '22 22:10

Arseny