【问题标题】:Using __str__() method in Django on Python 2在 Python 2 上的 Django 中使用 __str__() 方法
【发布时间】:2015-04-18 14:03:38
【问题描述】:

我正在使用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

【问题讨论】:

  • 答案已经在 cmets 中了!
  • 接受的答案应该是来自@alfetopito 的答案,因为这种技术最符合 Django 的移植理念。

标签: python django python-2.7 django-models


【解决方案1】:

为了保持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 的移植理念。

【讨论】:

  • 我刚刚传递了这篇文章,我想很高兴地注意到,如果您尝试使用一个调用其父级__str__ 的子级__str__,您可以创建一个recursion depth exception装饰师。需要注意的事情。对不起,死灵。
【解决方案2】:

可以,您只需将__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 值。

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 2018-05-27
    • 2013-12-13
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多