当调用str()
返回字段中带有特殊字符的 Django 模型对象时,在这种情况下,字符é将按\xc3\xa9
预期返回\xe9
。问题是什么?
我正在使用 Django 1.5.1,#coding=utf-8
并且from __future__ import unicode_literals
按照django 文档中的建议。
我只实现了__unicode__
方法而不是__str__
方法,因为Django__unicode__
在调用str()
.
这是一个代码示例(不是真正的生产代码)。
测试.py
# coding=utf-8
from __future__ import unicode_literals
from django.test import TestCase
from unicodebug.models import MyModel
class TestMyModel(TestCase):
def test_mymodel_str(self):
mymodel = MyModel(name='Chéri')
self.assertEqual(str(mymodel), 'Chéri')
def test_mymodel_unicode(self):
mymodel = MyModel(name='Chéri')
self.assertEqual(unicode(mymodel), 'Chéri') # using unicode() works fine!
模型.py
# coding=utf-8
from __future__ import unicode_literals
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
运行测试时在终端中输出。
(venv)frecon test$ python manage.py test unicodebug
Creating test database for alias 'default'...
/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py:501: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
if not first == second:
F.
======================================================================
FAIL: test_mymodel_str (unicodebug.tests.TestMyModel)
----------------------------------------------------------------------
Traceback (most recent call last):
File "unicodebug/tests.py", line 10, in test_mymodel_str
self.assertEqual(str(mymodel), 'Chéri')
AssertionError: 'Ch\xc3\xa9ri' != u'Ch\xe9ri'
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=1)
Destroying test database for alias 'default'...