Django unicode方法不起作用

时间:2015-11-17 07:38:22

标签: django python-2.7 unicode

我正在关注Django网站上的应用教程并使用 Python 2.7.5 Django 1.8 。它建议Python 2.7用户在models.py文件中包含 unicode 方法,以在python shell中返回可读输出。

我已将unicode方法添加到Question和Choice类中:

from django.db import models
import datetime
from django.utils import timezone
from django.util.encoding import python_2_unicode_compatible

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

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

    def __unicode__(self):
        return u"%i" % self.question_text

    def __str__(self):
        return question_text

class Choice(models.Model):
    question = models.ForeignKey(Question)

    choice_text = models.CharField(max_length=200)

    votes = models.IntegerField(default=0)

    def __unicode__(self):
        return u"%i" % self.choice_text
    def __str__(self):
        return choice_text

这是我在python shell中的输出:

from polls.models import Question, Choice
>>> Question.objects.all()
[<Question: Question object>]
>>> 

当真的应该是这样的时候:

>>> Question.objects.all()
[<Question: What's up?>]

我不明白我做错了什么。请帮忙!

3 个答案:

答案 0 :(得分:4)

was_published_recently__unicode__方法都不属于Question类。缩进很重要:确保它们缩进到与字段相同的级别。

答案 1 :(得分:0)

实际上您还应该定义__str__方法。 __unicode__将用于显式unicode调用。

最好使用python_2_unicode_compatible中的django.utils.encoding装饰器,您只会定义__str__方法。

@python_2_unicode_compatible
class A(object):
    def __str__(self):
        # your code

此方法也与python3兼容。

答案 2 :(得分:0)

我已经找到了如何正确地做到这一点(我在教程中使用python 2.7.11和django 1.9.2在virtualenv中):

from __future__ import unicode_literals
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)

    def __unicode__(self):
        return unicode(self.question_text)

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

    def __unicode__(self):
        return unicode(self.choice_text)

现在从项目目录的基础运行manage.py文件,如下所示:

$ python manage.py shell

这会加载IPython,但会为您设置所有适当的环境变量,以便轻松导入您的应用程序(让我们称之为&#39;民意调查&#39;这就是教程称之为I相信)。现在让我们来试试吧 我们刚用manage.py:

调用的IPython解释器
>>> from polls.models import Question, Choice
>>> Question.objects.all()
[]
>>> q = Question(question_text="I am now unicode!")
>>> q.save()
>>> Question.objects.all()
[<Question: I am now unicode!>]