Darwin
Darwin

Reputation: 338

Translate on Serializing Django Rest Framework

I want to Translate the variables "name" and "description" of my CategorySerializer, when serializing.

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')

Is the serializer method field a good aproach?

PD: this names are translated on the django.po.

Upvotes: 3

Views: 4483

Answers (2)

origamic
origamic

Reputation: 1116

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)

If you want, you can change fields' name as "name" and "description". And then;

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

Upvotes: 5

Can Arsoy
Can Arsoy

Reputation: 116

Yes, simply define a SerializerMethodField and return the translation on the fly. The following example changes the field 'description' to '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

Upvotes: 3

Related Questions