我正在学习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表之间的一对多关系,因此我们有了一组“选项”吗?