我刚刚开始学习Python,并开始研究Django.所以我从教程中复制了这段代码:
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def ___unicode__(self):
return self.choice #shouldn't this return the choice
Run Code Online (Sandbox Code Playgroud)
当我在shell中玩它时,我只是得到了Poll对象的"问题",但由于某种原因它不会返回Choice对象的"选择".我没有看到差异.我在shell上的输出如下所示:
>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
Run Code Online (Sandbox Code Playgroud)
我期待Choice对象返回"Choice object"之外的其他内容.有没有人知道我失败的地方和我应该注意什么?
编辑:让我觉得自己像个白痴的方式.是的,三个下划线是问题所在.我现在看了大约一个小时.
你在Choice类的"unicode__"之前有三个下划线,它应该只有两个像你的Poll类一样,如下所示:
def __unicode__(self):
return u'%s' % self.choice
Run Code Online (Sandbox Code Playgroud)