python - <model>_set 在我的 Django 模型中来自哪里?

标签 python django

我正在阅读 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()
[]

此示例使用的是带有问题和答案选择的 Poll 模型,定义如下:

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 表之间的一对多关系,因此我们有一组选择?

最佳答案

choice_set 由 Django ORM 自动放置在那里,因为您有一个从 ChoicePoll 的外键。这使得查找特定 Poll 对象的所有 Choice 变得容易。

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

您可以将带有related_name 参数的字段名称设置为ForeignKey

关于python - <model>_set 在我的 Django 模型中来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14483227/

相关文章:

python - 配置 Django

python - 无法在 Django 1.9+ 中解析 'django.utils.log.NullHandler'

python - 表单中的 Django ClearableInputField 不会以 HTML 形式呈现

python - 使用 to_representation 自定义 Django 序列化器输出

python - 使用 Python pandas 根据条件将行值复制到另一列

python - 为 Python/Pydev 编写自定义代码分析工具?

django - NGINX 配置中的 proxy_pass 选项有什么作用?

python - 使用 python 脚本删除 Windows 临时文件

python - 如何在 Python 中更好地控制循环增量?

python - Django Rest Framework 给出错误 : You do not have permission to perform this action