Python 停留在官方的Django教程上
我刚开始学习Python,也开始研究Django。所以我从教程中复制了这段代码:Python 停留在官方的Django教程上,python,django,Python,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.que
# 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
当我在shell中使用它时,我只得到Poll对象的“问题”,但由于某些原因,它不会返回choice对象的“选择”。我看不出有什么区别。我在shell上的输出如下所示:
>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
def __unicode__(self):
return u'%s' % self.choice
>>Poll.objects.all()
[]
>>>Choice.objects.all()
[, ]
>>>
我希望Choice对象返回的不是“Choice对象”。有没有人知道我在哪里失败了,我应该做些什么
编辑:让我觉得自己像个白痴。是的,三个下划线是问题所在。我已经看了大约一个小时了。在Choice类的“unicode”前面有三个下划线,在Poll类中应该只有两个,如下所示:
>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
def __unicode__(self):
return u'%s' % self.choice
Unicode方法的下划线太多。应改为:
def __unicode__(self):
return u'%s' % self.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
致:
你在第二个
\uuuuu unicode\uuuu
定义中的下划线太多了Django官方书籍有点过时了。但是对这些段落的评论真的很有用。它应该是两个下划线:
___unicode__(self):
应该是
\uuuu unicode\uuuuuu(self):
Draw。。。好吧,你跑得更快;-)别担心,我们都有犯愚蠢错误的时候;)