Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python <;模型>_在我的Django模型中是从哪里来的?_Python_Django - Fatal编程技术网

Python <;模型>_在我的Django模型中是从哪里来的?

Python <;模型>_在我的Django模型中是从哪里来的?,python,django,Python,Django,我正在学习Django教程: 我正在看一个将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

我正在学习Django教程:

我正在看一个将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()
现在我不明白对象选择集是从哪里来的。对于一个问题,我们有一组“选择”。但这在哪里有明确的定义?我只是觉得有两类定义。models.foreignKey(Poll)方法是否连接这两个类(因此是表)?
那么在choice_set中后缀“_set”来自哪里呢。是不是因为我们隐式地定义了投票表和选择表之间的一对多关系,所以我们有了一组选择

choice\u set
由Django ORM自动放在那里,因为您有一个从
choice
Poll
的外键。这使得查找特定
轮询
对象的所有
选项
s变得容易

因此,它在任何地方都没有明确定义

您可以使用
related\u name
参数将字段名设置为
ForeignKey

但这在哪里有明确的定义

事实并非如此;这是Django magic

我只是觉得有两类定义。models.foreignKey(Poll)方法是否连接这两个类(因此是表)

那么在choice_set中后缀“_set”来自哪里呢。是不是因为我们隐式地定义了投票表和选择表之间的一对多关系,所以我们有了一组选择


对。这只是违约;您可以通过显式设置名称。

关系
\u set
命令-在本例中
choice\u set
-是关系的API访问器(即ForeignKey、OneToOneField或ManyToManyField)


您可以阅读有关Django关系、关系API和
\u set

确定的更多信息。因此,请澄清一下——如果我有一对类似的表Table1和Table2(在模型中定义为python类),那么如果Table2将Table1的键作为外键,那么将隐式创建一个名为Table2_set(小写字母为“t”)的对象?@JJG:是的,这是正确的。尽管不要叫他们桌子。表是数据库中的内容。这些被称为“模型”。