我的Django模型中的 <model>_set 来源于哪里?

6 投票
3 回答
2024 浏览
提问于 2025-04-17 13:25

我正在学习Django的教程:https://docs.djangoproject.com/en/dev/intro/tutorial01/

我在看一个关于如何用manage.py使用python命令行的例子。下面的代码片段是从网站上复制的:

    # 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 个回答

1

那么这个是在哪里明确规定的呢?

其实并没有;这就是Django的魔法。

我觉得有两个类被定义了。models.foreignKey(Poll)这个方法是用来连接这两个类(也就是表)的吗?

没错。

那么choice_set中的后缀"_set"是从哪里来的呢?是因为我们在Poll和Choice表之间隐式定义了一种一对多的关系,所以我们有一组选择吗?

对的。这只是一个默认的命名方式;你可以通过正常的机制来明确设置这个名字。

2

这里提到的 _set 命令,比如 choice_set,是用来访问关系的一个工具(也就是外键、单一关系或多对多关系)。

如果你想了解更多关于 Django 中的关系、关系 API 以及 _set 的内容,可以点击 这里

6

choice_set 是 Django 的一个功能,它会自动生成,因为你在 ChoicePoll 之间有一个外键关系。这意味着你可以很方便地找到某个特定的 Poll 对象对应的所有 Choice

所以,这个 choice_set 并不是在代码的某个地方明确写出来的。

如果你想给这个字段起个名字,可以在 ForeignKey 中使用 related_name 参数来设置。

撰写回答