Dan Ganiev
Dan Ganiev

Reputation: 1062

How to select all objects that are foreign keyed from another model in django?

Sorry for title, I do not know how else to express myself.

For example, I have this three models:

class Person(models.Model):
    name = models.CharField()

class Teacher(models.Model):
    person = models.ForeignKey(Person)
    subject = models.CharField()

class Student(models.Model):
    person = models.ForeignKey(Person)
    grade = models.CharField()

How can I select all Person models that are Teachers?

Upvotes: 3

Views: 197

Answers (1)

Person.objects.filter(teacher__isnull=False) 
# return Person who has a teacher pointing to it

Upvotes: 6

Related Questions