This post first appeared here If you are a Django developer, you have probably heard of the great Django Rest Framework. It is simply one of the best, most powerful frameworks to build RESTFul Web APIs.
Recently, in one of our company projects we decided to build a Rest API. But as an extra requirement, it had to support model translations in order to provide multilingual content in our database.
In previous projects we used our own in-house solution. Although its core implementation was basically similar to most model translation API's, it lacked the “API” component, in other words, a set of reusable methods to ease the development pain especially when switching across different projects.
That's when we met django-hvad a very powerful Model Translation API, with an awesome community and a very promising future.
In this post, we are going to understand how we can make Django Rest Framework (DRF) work alongside a Model Translation API such as django-hvad. We assume that you are familiar with the basics of DRF and django-hvad.
Please note that the versions that we are going to be talking about are djangorestframework==2.4.3 and django-hvad==1.0.0 and you can easily install both of them through PIP.
Note also that future versions of django-hvad will have official DRF support as mentioned here, but at the time of the writing of this Post this was still work in progress. Basically in older versions we will need some of the “glue” provided here to make these two work nicely.
After installing DRF and django-hvad, we should create our own “custom” model serializers that will be used as a base to all of our Translatable Models. From there, you just inherit your serializers from TranslatableModelSerializer or HyperlinkedTranslatableModelSerializer.
When posting, you should simply add language_code as a normal field as part of your JSON / XML / etc.
After this, things become really straight forward. For example:
The company has been quite impressed with the advantages that django-hvad has brought to the table. We are definitely going to use them in future projects that require model translations and a Django Rest Framework API.