Getting all objects referenced in a foreign key field

一笑奈何 提交于 2021-02-10 15:42:46

问题


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}


回答1:


I figured it out,

Person.objects.exclude(director__set=None)



回答2:


First you need get the person:

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

Then, get all his movies:

person.movie_set.all()



来源:https://stackoverflow.com/questions/11442882/getting-all-objects-referenced-in-a-foreign-key-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!