5

I'm using django-rest-framework and I have a model "TextElement" with attribute "text" translated using django-modeltranslation. I need to create a generic serializer that takes translated fields and returns as data a dictionary with language as the key and the translated attribute as value. Example:

text_element = TextElement.objects.get(id=1)
text_element_serializer = TextElementSerializer(text_element)
text_element_serializer.data
>> {"text": {"en": "Something", "es": "Algo"}, "other_attribute": "Something else"}

I could do it using the following serializer:

class TextElementSerializer(serializer.ModelSerializer):
    text = serializer.SerializerMethodField()

    class Meta:
        model = TextElement
        fields = ('text', 'other_attribute')

    def get_text(self, instance):
        return {
            'en': instance.text_en,
            'es': instance.text_es
        }

But I would like to know if it's possible to create a genereic serializer that checks automatically all the translated attributes in "fields", using available languages in settings.LANGUAGES and returning the same data structure.

Thanks in advance!

JBarrioGarcía
  • 165
  • 2
  • 11

0 Answers0