0

Following model allows me to handle translations in the database without adjusting code in order to add a language.

class NameString(models.Model)
    en = models.CharField(max_length=55)
    de = models.CharField(max_length=55)

Example use in model called Item:

class Item(models.Model):
    name = models.ForeignKey(NameString)

I use a ReadOnlyModelViewSet to view through an api. Which returns the following json:

"results": [
    {
        "id": 1,
        "name": 3,
    }
]

I would like to replace the id value in name field of the json with the actual name in a given language. This is possible by annotating the queryset as for example:

name_field = 'name__{}'.format(self.language())
queryset = Item.objects.annotate(name_value=F(name_field))

If I use a serializer with a value name_value, I get the following json:

"results": [
    {
        "id": 1,
        "name_value": 'cucumber',
    }
]

My question is: how do I write a manager that would handle the items ManyToMany field in the ItemList model so that it returns a queryset in a specified language?

class ItemList(models.Model):
    items = models.ManyToManyField(Item)

So that I get a following json:

"results": [
    {
        "id": 1,
        "name": "item_list_1",
        "items" [
            {
                "id": 1,
                "name_value": "cucumber"
            },
            {
                "id": 2,
                "name_value": "apple"
            }  
        ],
    }
]
Jura Brazdil
  • 970
  • 7
  • 15

2 Answers2

0

I found out about a different functionality that solved my problem without the need of the manager. You can simply overwrite json field names in class view serializers with a serializer method field in the following way:

class MySerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField('get_name_value')

class Meta:
    model = MyModel
    fields = (
        "id",
        "name",
    )

def get_name_value(self, obj):
    return obj.name_value
Jura Brazdil
  • 970
  • 7
  • 15
0

Even more elegant solution!

class MySerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='name_value')

    class Meta:
        model = MyModel
        fields = (
            "id",
            "name",
        )
Jura Brazdil
  • 970
  • 7
  • 15