Django model fields in many languages
So I found myself in a situation where I needed to have multilingual support for the DB in Django. i18n does a great job for static messages, but what about all that dynamic data, ie. news in multiple languages. Sure you could create a column per language you want to support but that’s an awful waste on the table, plus when you want to start supporting additional languages you have to alter the table to add columns — not a best, and definetly not the most user friendly way.
Another way around the problem is to create separate table for each table that requires multilingual fields. Every translation table would have a ForeignKey to the parent table and consist of all the fields that need to be in a specific language plus either a field or ForeignKey to a table that has the language code (for queries/identification which language is used).
I’ve created
django-multilingual-model to do just that and make it easier to use/query such tables.
Here’s an example:
class Language(models.Model):
code = models.CharField(max_length=5)
name = models.CharField(max_length=16)
class BookTranslation(models.Model):
language = models.ForeignKey("Language")
title = models.CharField(max_length=32)
description = models.TextField()
model = models.ForeignKey("Book")
class Book(MultilingualModel):
ISBN = models.IntegerField()
class Meta:
translation = BookTranslation
multilingual = ['title', 'description']
lang_en = Language(code="en", name="English")
lang_en.save()
lang_pl = Language(code="pl", name="Polish")
book = Book(ISBN="1234567890")
book.save()
book_en = BookTranslation()
book_en.title = "Django for Dummies"
book_en.description = "Django described in simple words."
book_en.model = book
book_en.save()
book_pl = BookTranslation()
book_pl.title = "Django dla Idiotow"
book_pl.description = "Django opisane w prostych slowach"
book_pl.model = book
book_pl.save() # now here comes the magic
book.title_en
u'Django for Dummies'
book.description_pl
u'Django opisane w prostych slowach'
Read More



