Django教程choice_set

时间:2013-07-10 08:41:02

标签: django django-models

来自Django教程:

我已将我的模型定义如下:

from django.db import models
import datetime
from django.utils import timezone

# Create your models here.

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):  # Python 3: def __str__(self):
        return self.question
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __unicode__(self):  # Python 3: def __str__(self):
        return self.choice_text

在哪里定义了choice_set,这是如何工作的?

>>> p = Poll.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()

2 个答案:

答案 0 :(得分:4)

我不知道你想要的解释有多深,但当你poll = models.ForeignKey(Poll)时,Django会为你定义。

You can read here about it.

答案 1 :(得分:0)

choice_set未在任何地方定义。

Django为关系的“其他”方创建API访问器 - 从相关模型到定义关系的模型的链接。例如,Poll对象p可以通过choice_set属性访问所有相关Choice对象的列表:p.choice_set.all()。

所以choice_set。选择是小写的选择模型,_set是一种Django Manager工具。

详细信息,您可以阅读right here