Search code examples
djangotastypie

How to use tastypie for multilingual API in Django?


I am using django-transmeta for internalization of my models. It is working very well. It is saving the models into the database like this:

name_en, name_de, name_tr ...

so when you need object.name, it returns the name in current locale, whic is very good for my task.

I am using tastypie for the RESTful API. Tastypie returns all columns of the table (name_en, name_de, name_tr). What I want is, making a request like :

http://127.0.0.1:8000/api/object/?format=json&lang=en

So server should response only the name (not name_en, name_de, name_tr) in English.

How can I do that? What tastypie function, customization can handle this?

Update:

 def dehydrate_title(self, bundle):
        return bundle.data['title'].upper() 

Something liked that can be a solution?


Solution

  • Below model solved my problem. Thank you kgr!

    from tastypie.resources import ModelResource
    from padmenu.item.models import Item
    from django.utils.translation import activate
    from tastypie import fields
    
    
    class ItemResource(ModelResource):
        name = fields.CharField()
        description = fields.CharField()
        class Meta:
            queryset = Item.objects.all()
            resource_name = 'item'
            excludes = ['name_tr', 'name_de', 'name_en', 'description_tr', 'description_de',   'description_en']
    
    def dehydrate(self, bundle):
        lang = str(bundle.request.GET.get('lang'))
        activate(lang)
        bundle.data['name'] = bundle.obj.name
        bundle.data['description'] = bundle.obj.description
        return bundle