我正在学习Django教程:https://docs.djangoproject.com/en/dev/intro/tutorial01/
我看的是在manage.py中使用python shell的例子。代码片段是从网站复制的:
# 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()
现在我不明白object choice_set是从哪里来的。对于一个问题,我们有一组“选择”。但是这是在哪里明确定义的呢?我只是好像定义了两个类。Models.foreignKey(轮询)方法是否连接了这两个类(因此是表)?现在,在choice_set中,后缀"_set“来自哪里。
发布于 2013-01-23 15:35:33
Django ORM会自动将choice_set
放在那里,因为您有一个从Choice
到Poll
的外键。这使得查找特定Poll
对象的所有Choice
变得很容易。
因此,没有在任何地方显式地定义它。
您可以使用related_name
参数将字段的名称设置为ForeignKey
。
发布于 2013-01-23 15:39:46
关系API命令-在本例中为choice_set
-是关系的_set
访问器(即,ForeignKey、OneToOneField或ManyToManyField)。
您可以阅读有关Django关系、关系API和_set
here的更多信息。
发布于 2013-01-23 15:36:16
但是这是在哪里明确定义的呢?
不是的,这是Django的魔法。
,我好像定义了两个类。Models.foreignKey(轮询)方法是否连接了这两个类(因此是表)?
对,是这样。
现在choice_set中的后缀"_set“是从哪里来的。是不是因为我们隐含地定义了Poll和Choice表之间的一对多关系,因此我们有了一组选择?
是。这只是一个默认值;您可以通过the normal mechanism显式设置名称。
https://stackoverflow.com/questions/14483227
复制