在Python 2上的Django中使用__str __()方法 [英] Using __str__() method in Django on Python 2
问题描述
我正在使用 Django项目教程来学习Django。 。
因为我使用python 2.7,所以无法在python 2.7中实现以下功能:
来自django.db导入模型
class Question(models.Model):
#...
def __str __(self):#__unicode__ on Python 2
返回self.question_text
类Choice(models.Model):
#...
def __str __(self):#__unicode__ on Python 2
返回self.choice_text
为使py2和py3之间的代码兼容,更好的方法是使用装饰器 python_2_unicode_compatible
。
这样,您可以保留 str 方法:
从django.db导入模型来自django.utils.encoding的
导入python_2_unicode_compatible
@ python_2_unicode_compatible
类问题(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
参考:< a href = https://docs.djangoproject.com/zh-CN/1.8/topics/python3/#str-and-unicode-methods rel = noreferrer> https://docs.djangoproject.com/zh/1.8 / topics / python3 /#str-and-unicode-methods
Django提供了一种简单的方法来定义 str适用于Python 2和3的()和 unicode ()方法,您必须定义 str ()方法返回文本并应用python_2_unicode_compatible()装饰器。
...
此技术是Django移植哲学的最佳选择。
I am Learning Django using the Django project tutorial. Since I use python 2.7 I am unable to implement the following in 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
To keep the code compatible between py2 and py3, a better way is to use the decorator python_2_unicode_compatible
.
This way you can keep the str method:
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
Reference: https://docs.djangoproject.com/en/1.8/topics/python3/#str-and-unicode-methods
Django provides a simple way to define str() and unicode() methods that work on Python 2 and 3: you must define a str() method returning text and to apply the python_2_unicode_compatible() decorator.
...
This technique is the best match for Django’s porting philosophy.
这篇关于在Python 2上的Django中使用__str __()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!