Django教程:什么是choice_set? [英] Django tutorial: What is choice_set?
问题描述
在Django教程中有这一行,编写你的第一个Django app,part 1 :
There is this line in the Django tutorial, Writing your first Django app, part 1:
p.choice_set.create(choice='Not much', votes=0)
如何 choice_set
存在,它是什么?
我认为选择
part是模型的小写版本选择
在教程中使用,但什么是 choice_set
?您可以详细说明吗?
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?
更新1 :根据Ben James '答案我在文档中找到了一个描述的地方: 关系后退 。
Update 1: based on Ben James' answer I located a place in the documentation where it is described: Following relationships "backward".
推荐答案
您在选择
中创建了一个外键,其中每个都与 code>。
You created a foreign key on Choice
which relates each one to a Question
.
所以,每个选择
显式地有一个 code>字段,您在模型中声明。
So, each Choice
explicitly has a question
field, which you declared in the model.
Django的ORM从向后追溯关系问题
在每个实例上自动生成一个名为 foo_set
的字段,其中 Foo
是具有 ForeignKey
这个模型的字段。
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
是一个回覆latedManager
可以创建与问题
实例相关的选项
对象的查询。 q.choice_set.all()
choice_set
is a RelatedManager
which can create querysets of Choice
objects which relate to the Question
instance, e.g. q.choice_set.all()
如果你不喜欢 foo_set
命名Django自动选择,或者如果您有同一型号的多个外键需要区分它们,则可以使用 related_name
参数 ForeignKey
。
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
.
这篇关于Django教程:什么是choice_set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!