关于序列化Django Rest Framework的翻译

时间:2017-11-20 15:00:11

标签: django serialization django-rest-framework

我希望在序列化时翻译我的CategorySerializer的变量“name”和“description”。

from rest_framework import serializers
from api.models import Category
from django.utils.translation import ugettext_lazy as _

class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = ('id', 'name', 'image', 'description')

序列化方法方法是一个很好的方法吗?

PD:这个名字在django.po上翻译。

2 个答案:

答案 0 :(得分:3)

<强> serializers.py

from rest_framework import serializers
from api.models import Category
from django.utils.translation import ugettext_lazy as _

class CategorySerializer(serializers.ModelSerializer):
    name_ = serializers.ReadOnlyField(source='get_name')
    description_ = serializers.ReadOnlyField(source='get_description')

    class Meta:
        model = Category
        fields = ('id', 'name', 'image', 'description')

    def get_name(self):
        return _(self.name)

    def get_description(self):
        return _(self.name)

如果需要,可以将字段名称更改为“名称”和“描述”。然后;

def to_representation(self, instance):
    """
    Object instance -> Dict of primitive datatypes.
    """
    ret = OrderedDict()
    fields = self._readable_fields


    for field in fields:
        try:
            attribute = field.get_attribute(instance)
        except SkipField:
            continue

        # We skip `to_representation` for `None` values so that fields do
        # not have to explicitly deal with that case.
        #
        # For related fields with `use_pk_only_optimization` we need to
        # resolve the pk value.
        check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
        if check_for_none is None:
            ret[field.field_name] = None
        else:

            # override to_representation function
            if field.field_name == "name" or field.field_name == "description":
                ret[field.field_name] = _(attribute)


    return ret

答案 1 :(得分:2)

是的,只需定义一个SerializerMethodField并即时返回翻译。以下示例将字段'description'更改为'translation':

class CategorySerializer(serializers.ModelSerializer):

    translation = SerializerMethodField('get_description_string')

    class Meta:
        model = Category
        fields = ('id','translation',)

    def get_description_string(self,obj):
        return obj.description