在此Django应用程序教程中,choice_set是什么?

问题:在此Django应用程序教程中,choice_set是什么?

Django教程中的这一行,编写您的第一个Django应用,第1部分

p.choice_set.create(choice='Not much', votes=0)

它是如何choice_set存在的?它是什么?

我想这choice部分是Choice本教程中使用的模型的小写版本,但是什么是choice_set?你能详细说明吗?

更新:根据Ben的回答,我找到了此文档:遵循“向后”关系

There is this line in the Django tutorial, Writing your first Django app, part 1:

p.choice_set.create(choice='Not much', votes=0)

How is choice_set called into existence and what is it?

I suppose the choice part is the lowercase version of the model Choice used in the tutorial, but what is choice_set? Can you elaborate?

UPDATE: Based on Ben‘s answer, I located this documentation: Following relationships “backward”.


回答 0

您创建了一个外键Choice,每个外键都与关联Question

因此,每个Choice显式都有一个question字段,您可以在模型中声明该字段。

Django的ORM也遵循这种关系Question,在每个实例上自动生成一个名为foo_setwhere Foo是模型的ForeignKey字段,其中包含该模型的字段。

choice_set是一个RelatedManager可以创建ChoiceQuestion实例相关的对象的查询集的,例如q.choice_set.all()

如果您不喜欢foo_setDjango自动选择的命名,或者您对同一个模型拥有多个外键并需要区分它们,则可以使用related_name参数to 来选择自己的替代名称ForeignKey

You created a foreign key on Choice which relates each one to a Question.

So, each Choice explicitly has a question field, which you declared in the model.

Django’s ORM follows the relationship backwards from Question too, automatically generating a field on each instance called foo_set where Foo is the model with a ForeignKey field to that model.

choice_set is a RelatedManager which can create querysets of Choice objects which relate to the Question instance, e.g. q.choice_set.all()

If you don’t like the foo_set naming which Django chooses automatically, or if you have more than one foreign key to the same model and need to distinguish them, you can choose your own overriding name using the related_name argument to ForeignKey.