来自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_textchoice_set是在哪里定义的,它是如何工作的?
>>> p = Poll.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()发布于 2013-07-10 16:43:49
我不知道你想要多深的解释,但是Django在你做poll = models.ForeignKey(Poll)的时候为你定义了它。
发布于 2013-12-10 00:10:59
没有在任何地方定义choice_set。
Django为关系的“另一端”创建API访问器-从相关模型到定义关系的模型的链接。例如,轮询对象p可以通过choice_set属性p.choice_set.all()访问所有相关选择对象的列表。
所以choice_set。其中choice是小写的选择模型,而_set是一种Django管理器工具。
更详细地说,你可以阅读right here 。
https://stackoverflow.com/questions/17566031
复制相似问题