在我的Django模型中,<model>_set是从哪里来的?

6
我正在学习Django教程:https://docs.djangoproject.com/en/dev/intro/tutorial01/ 我正在查看使用python shell和manage.py的示例。以下是从网站上复制的代码片段:
    # Give the Poll a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a poll's choices) which can be accessed via the API.
>>> p = Poll.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
[]

这个示例使用一个投票模型,包含问题和答案选项,定义如下:

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField()

现在我不明白选择对象choice_set是从哪里来的。对于一个问题,我们有一组“选项”。但这个定义在哪里?我只看到两个类被定义了。models.foreignKey(Poll)方法是否连接了这两个类(因此连接了表)? 那么,在choice_set中后缀“_set”是从哪里来的?是因为我们隐式地定义了Poll和Choice表之间的一对多关系,因此我们有了一组“选项”吗?

3个回答

6

choice_set是Django ORM自动添加的,因为你在Choice模型中有一个外键指向Poll模型。这使得查找特定Poll对象的所有Choice变得容易。

因此,它没有被明确地定义在任何地方。

你可以使用ForeignKeyrelated_name参数设置字段的名称。


好的。所以,只是为了澄清 - 如果我有一对类似的表Table1和Table2(在模型中定义为Python类),那么如果Table2将Table1的键作为外键,那么会隐式创建一个名为table2_set(小写“t”)的对象? - user485498
1
@JJG:是的,没错。虽然不要称它们为表格。表格是数据库中的内容。这些被称为“模型”。 - Lennart Regebro

2

_set 命令 - 在这个例子中是 choice_set - 是与关系(即 ForeignKey、OneToOneField 或 ManyToManyField)相关的 API 访问器。

你可以在这里了解更多关于 Django 关系、关系 API 和 _set 的信息。


1
“但是这个在哪里明确定义了呢?”
“没有明确定义;这是 Django 的魔法。”
“我只是看到两个类被定义了。models.foreignKey(Poll) 方法是否连接了这两个类(因此连接了这两个表格)?”
“没错。”
“现在,choice_set 中的后缀“_set”是从哪里来的?是因为我们隐式地定义了一个 Poll 和 Choice 表格之间的一对多关系,因此我们有了一组选择吗?”
“是的。这只是一个默认值;你可以通过 正常机制 显式设置名称。”

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接