【问题标题】:Django Unicode method is not workingDjango Unicode 方法不起作用
【发布时间】:2015-12-19 20:30:31
【问题描述】:

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

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

from django.db import models
import datetime
from django.utils import timezone

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?>]

我以前问过这个问题,但没有找到解决办法。请帮忙!

【问题讨论】:

    标签: python django unicode


    【解决方案1】:

    您不需要同时使用__unicode____str__。在 Python 2.7 中,您只需使用 __str__ 。您可以删除 __unicode__ 并单独使用 __str____unicode__ 适用于 python 3。

    在文档here 中了解更多信息

    【讨论】:

    【解决方案2】:

    要使 django unicode 与 python 2 和 3 兼容,请使用 python_2_unicode_compatible 装饰器。然后使用__str__ 作为unicodes:

    from django.utils import encoding
    
    @encoding.python_2_unicode_compatible
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
    
        def __str__(self):
           return self.question_text
    

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 2013-04-13
      • 2015-09-18
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      相关资源
      最近更新 更多