Bwmat
Bwmat

Reputation: 4578

Getting all objects referenced in a foreign key field

I have models similar to

class Person(Model):
    name = CharField(max_length=100)

class Movie(Model):
    ...
    director = ForeignKey(Person)

How would I get the set of all Person objects which are set as the director for any Movie object?

edit: to clarify, if my Movie 'table' consisted of two entries, one with director A and one with director B, and my Person 'table' consisted of the three entries A, B, and C, I would want to get the set {A, B}

Upvotes: 1

Views: 183

Answers (2)

Bwmat
Bwmat

Reputation: 4578

I figured it out,

Person.objects.exclude(director__set=None)

Upvotes: 2

carpediem
carpediem

Reputation: 11

First you need get the person:

my_person = Person.objects.get(name="XXX")

Then, get all his movies:

person.movie_set.all()

Upvotes: 1

Related Questions