2009-05-28 88 views
3

我剛剛開始學習Python,並開始研究一下Django。所以我複製這段代碼從教程:卡住官方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 

當我在外殼玩弄它,我剛拿到的投票對象的「問題」,但出於某種原因,它不會返回Choice對象的「選擇」。我看不出有什麼不同。我在shell上的輸出如下所示:

>>> Poll.objects.all() 
[<Poll: What is up?>] 
>>> Choice.objects.all() 
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>] 
>>> 

我期待Choice對象返回「Choice對象」以外的內容。有沒有人知道我失敗的地方以及我應該看什麼?

編輯:讓我覺得自己像一個白癡的方式。是的,這三個下劃線是問題所在。我現在正在看那個小時。

+2

別擔心,我們都曾經有過我們的時刻,當我們做愚蠢的錯誤;) – 2009-05-28 09:31:29

回答

8

您對Choice類「unicode__」前三下劃線,應該是隻有兩個像你的民意調查類,像這樣:

def __unicode__(self): 
    return u'%s' % self.choice 
4

你Unicode的方法有太多的下劃線。它應該閱讀:

def __unicode__(self): 
    return u'%s' % self.choice 
+0

抽獎! ...好吧,你快了;-) – 2009-05-28 09:21:02

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__定義

2

有太多的強調了官方的Django書有點過時。但是對段落的評論非常有用。它應該是兩個下劃線:

___unicode__(self): 

應該__unicode__(self):