被官方Django教程困住了
我刚开始学习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
当我在命令行里玩这段代码时,我只看到了Poll对象的“问题”,但不知道为什么它却没有返回Choice对象的“选项”。我看不出这两者有什么区别。我在命令行里的输出是这样的:
>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
我本来期待Choice对象能返回一些其他的内容,而不是“Choice object”。有没有人知道我哪里出错了,应该关注什么呢?
补充:让我感觉自己像个傻瓜。没错,三个下划线就是问题所在。我看了这个问题差不多一个小时。
4 个回答
3
修改:
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
为:
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
你在第二个 __unicode__
定义中用了太多下划线。
4
你的Unicode方法下划线太多了。应该是这样写:
def __unicode__(self):
return u'%s' % self.choice
7
在你的Choice类中,“unicode__”前面有三个下划线,其实应该只有两个,就像在你的Poll类里那样,应该是这样:
def __unicode__(self):
return u'%s' % self.choice