在Python 2上使用Django中的__str __()方法

时间:2015-02-17 18:50:28

标签: python django python-2.7 django-models

我正在使用Django project tutorial学习Django。 由于我使用python 2.7,我无法在python 2.7中实现以下内容:

from django.db import models

class Question(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.question_text

class Choice(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.choice_text

2 个答案:

答案 0 :(得分:15)

为了使代码在py2和py3之间保持兼容,更好的方法是使用装饰器python_2_unicode_compatible。 这样您就可以保留 str 方法:

from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Question(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.question_text

@python_2_unicode_compatible
class Choice(models.Model):
# ...
    def __str__(self):              # __unicode__ on Python 2
        return self.choice_text

参考:https://docs.djangoproject.com/en/1.8/topics/python3/#str-and-unicode-methods

  

Django提供了一种简单的方法来定义适用于Python 2和3的 str ()和 unicode ()方法:您必须定义 str ()方法返回文本并应用python_2_unicode_compatible()装饰器。

     

...

     

这种技术是Django移植哲学的最佳匹配。

答案 1 :(得分:7)

是的,您可以,只需将__str__替换为__unicode__,评论如下:

class Question(models.Model):
# ...
    def __unicode__(self):
        return self.question_text

class Choice(models.Model):
# ...
    def __unicode__(self):
        return self.choice_text

在该部分的下方,您会找到一些解释:

  

__str____unicode__?

     

在Python 3上,它很简单,只需使用__str__()

     

在Python 2上,您应该定义返回unicode值的__unicode__()方法。 Django模型有一个默认的__str__()方法,它调用__unicode__()并转换结果到UTF-8字节串。这意味着unicode(p)将返回Unicode字符串,str(p)将返回字节字符串,字符编码为UTF-8。 Python做的恰恰相反:object有一个__unicode__方法,它调用__str__并将结果解释为ASCII字节串。这种差异会造成混乱。

question_textchoice_text属性已经返回Unicode值。