jsondjangoannotationsmany-to-manydjango-custom-manager

Custom Default manytomany manager with a parameter


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"
            }  
        ],
    }
]

Solution

  • Even more elegant solution!

    class MySerializer(serializers.ModelSerializer):
        name = serializers.CharField(source='name_value')
    
        class Meta:
            model = MyModel
            fields = (
                "id",
                "name",
            )