【问题标题】:Stuck on official Django Tutorial坚持使用官方 Django 教程
【发布时间】:2009-05-28 09:13:27
【问题描述】:

我刚开始学习 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

当我在 shell 中使用它时,我只是得到 Poll 对象的“问题”,但由于某种原因,它不会返回 Choice 对象的“选择”。我看不出有什么区别。我在 shell 上的输出如下所示:

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

我期待 Choice 对象返回“Choice 对象”以外的其他内容。有人知道我失败的地方以及我应该研究什么吗?

编辑:让我觉得自己像个白痴的方式。是的,三个下划线是问题所在。我已经看了大约一个小时了。

【问题讨论】:

  • 别担心,我们都有犯愚蠢错误的时刻;)

标签: python django


【解决方案1】:

Choice 类的 "unicode__" 前面有三个下划线,在 Poll 类中应该只有两个,像这样:

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

【讨论】:

    【解决方案2】:

    您的 Unicode 方法有太多下划线。它应该是:

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

    【讨论】:

    • 抽奖! ...好吧,你更快 ;-)
    【解决方案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】:

      官方的 Django 书有点过时了。但是段落的 cmets 真的很有用。应该是两个下划线:

      ___unicode__(self):
      

      应该是__unicode__(self):

      【讨论】:

        猜你喜欢
        • 2018-11-29
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 2012-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-02
        相关资源
        最近更新 更多