Django教程 - 返回通用对象而非文本

1 投票
2 回答
1665 浏览
提问于 2025-04-21 05:03

我现在正在学习Django教程,当我想为我的投票创建一个选项时,却总是返回一个通用的选项,而不是我输入的文本。

In [19]: q.choice_set.all()
Out[19]: []

In [20]: q.choice_set.create(choice_text='Not much', votes=0)
Out[20]: <Choice: Choice object>

我得到的是'Choice object',而不是'Not much'。

这是我现有的mysite.settings路径的代码:

`class Question(models.Model):

quest_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __unicode__(self):
    return self.quest_text

def was_published_recently(self):
    return self.pub_date >= timezone.now()-datetime.timedelta(days=1)

class Choice(models.Model):

question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __unicode___(self):
    return self.choice_text`

现在我得到了这个:

In [17]: Question.objects.all() Out[17]: <repr(<django.db.models.query.QuerySet at 0x10530bbd0>) failed: AttributeError: 'Question' object has no attribute 'unicode'>

2 个回答

3

你调用的方法其实是在创建并返回一个新的 Choice 对象,而不是一个新的 str 实例。所以在 REPL(交互式编程环境)里你看到的正是你应该看到的:<Choice: Choice object> 是 Choice 实例的默认显示方式。

如果你不喜欢这个默认的显示方式,可以实现 __unicode____repr__ 方法(或者在 Python 3 及以上版本中用 __str__):

class Choice(models.Model):
    # ... other stuff you already have here ...

    def __unicode__(self):
        return self.choice_text

    def __repr__(self):
        return self.unicode()

这个内容可能在教程后面会讲到,所以在这里提问之前,先把教程看完是个好主意。

3

因为 <Choice: Choice object> 这个表示方式对这个对象来说并不太有用,所以你可以给每个模型添加一个 __str__() 方法(在Python 2中用 __unicode__())。

class Question(models.Model):
    #.. Other model stuff you already have 
    def __str__(self):             
        return self.question_text

class Choice(models.Model):
    # ... Other model stuff you already have 
    def __str__(self):              
        return self.choice_text

撰写回答