Django-tastypie:utf8不正确

时间:2016-08-29 00:48:28

标签: python django unicode utf-8 tastypie

class ActionResource(ModelResource):

    class Meta:
        queryset = ActionInfo.objects.all()
        resource_name = 'action'

    def dehydrate(self, bundle):
        bundle.data['name'] = bundle.obj.name
        bundle.data['expect_time'] = bundle.obj.expect_time
        bundle.data['type'] = bundle.obj.type
        bundle.data['price'] = bundle.obj.price
        bundle.data['additional'] = bundle.obj.additional
        return bundle

来自resource.py的此代码。有俄语字母的Charfields打印不正确,例如:名称:“Солянка”。我在resource.py:

的顶部添加了
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

并从django模型中返回字符串:

class ActionName(models.Model):
    name = models.CharField(max_length=300) 
    def __str__(self):
        return self.name

class ActionInfo(models.Model):
    name        = models.ForeignKey(ActionName,     related_name="title",    on_delete=models.CASCADE, null=True, blank=True)
    expect_time = models.ForeignKey(ActionDuration, related_name="duration",on_delete=models.CASCADE, null=True, blank=True)
    type        = models.ForeignKey(ActionType,     related_name="type",    on_delete=models.CASCADE, null=True, blank=True)
    available   = models.NullBooleanField(null=True, blank=True, default=True)
    price       = models.ForeignKey(ActionPrice,    related_name="price",   on_delete=models.CASCADE, null=True, blank=True)
---------------------------------------------

返回了json:

{
additional: " 280 Рі ",
available: true,
comments: null,
discription: "",
expect_time: null,
id: 120,
name: "Солянка",
photo: "/images/83913-220-184-solyanka_2.jpg",
rate: null,
resource_uri: "/api/v1/action/120/",
type: "Первые блюда",
}

谁知道如何解决?)

1 个答案:

答案 0 :(得分:1)

而不是__str__()使用__unicode__()。并使用smart_text

from django.utils.encoding import smart_text

class ActionName(models.Model):
    name = models.CharField(max_length=300) 
    def __unicode__(self):
        return smart_text(self.name)

BTW:而不是dehydrate()使用字段:

from tastypie import fields

class ActionResource(ModelResource):
    name = fields.CharField('name__name', null=True)

    class Meta:
        queryset = ActionInfo.objects.all()
        resource_name = 'action'

BTW2:

>>> print u'Солянка'.encode('windows-1251')
Солянка
>>> print u'Солянка'.encode('windows-1251').decode('utf8')
Солянка