我正在阅读 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 表之间隐式定义了一对多的关系,因此我们有一组选择吗?