Skip to content
Drachenfels edited this page Sep 14, 2010 · 8 revisions

Defining translatable fields on a Model

Translatable fields on a model are defined using a nested class which must be a subclass of ``multilingual.translation.TranslationModel``.

An example of a multilingual news model::

    from django.db import models
    from multilingual.translation import TranslationModel
    class NewsEntry(models.Model):
        author = models.ForeignKey('auth.User')
        class Translation(TranslationModel):
            title = models.CharField(max_length=255)
            content = models.TextField()

The inner class must be named ``Translation``.

Accessing translatable fields

If you have an instance of the ``NewsEntry`` model above, you can access the translatable fields like this::

    news_entry = NewsEntry.objects.get(id=1)
    news_entry.title # the title in the current language
    news_entry.content # the content in the current language
    news_entry.author # the author

The current language is deteced the same way django detects it.

To enable multilingual in the backend

    from news.models import NewsEntry
    from django.contrib import admin
    from multilingual.admin import MultilingualModelAdmin
    class NewsEntryAdmin(MultilingualModelAdmin):
        pass
    admin.site.register(NewsEntry, NewsEntryAdmin)

How to find a news entry in given language:

    from multilingual.utils import GLL # GlobalLanguageLock
    GLL.lock('en')
    news_entry = NewsEntry.objects.exclude(title__exact='', id__exact=1) # you will receive NewsEntry of id = 1 only, if there is translation of it to english
    news_entry.title # the title in english
    news_entry.content # the content in english
    news_entry.author # the author
    GLL.release()

However there is a catch, if we want one news picked at random among news that have translation in english, this wont work as expected:

    from multilingual.utils import GLL # GlobalLanguageLock
    GLL.lock('en')
    news_entry = NewsEntry.objects.all().order_by('?')
    GLL.release()

Lets assume there is no news with translation to english, thus we should have news_entry = None, however we still are going to receive object that has translation to any other language.

Either this wont work as expected:

    from multilingual.utils import GLL # GlobalLanguageLock
    GLL.lock('en')
    news_entry = NewsEntry.objects.get(id=1)
    GLL.release()

In this case you will receive NewsEntry that is kept under id = 1, no matter if it has any translation or not.