我正在阅读 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 自动放置在那里,因为您有一个从 Choice
到 Poll
的外键。这使得查找特定 Poll
对象的所有 Choice
变得容易。
因此没有在任何地方明确定义。
您可以将带有related_name
参数的字段名称设置为ForeignKey
。
关于python - <model>_set 在我的 Django 模型中来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14483227/