Reference: Context

This module contains the context managers for the Translations app.

Important

The examples are assumed to CRUD this dataset.

Type\Lang

English

German

Continent

Europe

Europa

Asia

Asien

Country

Germany

Deutschland

South Korea

Südkorea

City

Cologne

Köln

Seoul

Seul

Please memorize this dataset in order to understand the examples better.

class translations.context.Context[source]

A context manager which provides custom translation functionalities.

Provides CRUD functionalities like create(), read(), update() and delete() to work with the translations and also some other functionalities like reset() to manage the Context.

To use Context:

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.all()
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:
    context.read('de')    # read the translations onto the context
    print(':')            # use the objects like before
    print(continents)
    print(continents[0].countries.all())
    print(continents[0].countries.all()[0].cities.all())

    continents[0].countries.all()[0].name = 'Change the name'
    context.update('de')  # update the translations from the context

    context.delete('de')  # delete the translations of the context

    context.reset()       # reset the translations of the context
    print(':')            # use the objects like before
    print(continents)
    print(continents[0].countries.all())
    print(continents[0].countries.all()[0].cities.all())
:
<TranslatableQuerySet [
    <Continent: Asien>,
    <Continent: Europa>,
]>
<TranslatableQuerySet [
    <Country: Deutschland>,
]>
<TranslatableQuerySet [
    <City: Köln>,
]>
:
<TranslatableQuerySet [
    <Continent: Asia>,
    <Continent: Europe>,
]>
<TranslatableQuerySet [
    <Country: Germany>,
]>
<TranslatableQuerySet [
    <City: Cologne>,
]>
__init__(entity, *relations)[source]

Initialize a Context for an entity and some relations of it.

Defines the entity and the relations of it as the Context‘s purview.

Parameters:
  • entity (Model or Iterable(Model)) – The entity to initialize the Context for.

  • relations (list(str)) – The relations of the entity to initialize the Context for. Each relation may be divided into separate parts by LOOKUP_SEP (usually __) to represent a deeply nested relation. Each part must be a related_name.

Raises:

TypeError

  • If the entity is neither a model instance nor an iterable of model instances.

  • If the model of the entity is not Translatable.

  • If the models of the relations are not Translatable.

To Initialize a Context for an entity (an instance) and some relations of it:

from translations.context import Context
from sample.models import Continent

europe = Continent.objects.get(code='EU')
relations = ('countries', 'countries__cities',)

# initialize context
with Context(europe, *relations) as context:
    print('Context Initialized!')
Context Initialized!

To Initialize a Context for an entity (a queryset) and some relations of it:

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.all()
relations = ('countries', 'countries__cities',)

# initialize context
with Context(continents, *relations) as context:
    print('Context Initialized!')
Context Initialized!

To Initialize a Context for an entity (a list of instances) and some relations of it:

from translations.context import Context
from sample.models import Continent

continents = list(Continent.objects.all())
relations = ('countries', 'countries__cities',)

# initialize context
with Context(continents, *relations) as context:
    print('Context Initialized!')
Context Initialized!

Note

It is recommended for the relations of the entity to be prefetched before initializing a Context, in order to reach optimal performance.

To do this use select_related(), prefetch_related() or prefetch_related_objects().

_get_changed_fields()[source]

Yield the info about the changed fields in the Context‘s purview.

Yields the info about the changed fields in the TranslatableMeta.fields of the Context‘s purview.

Returns:

The info about the changed fields in the Context‘s purview.

Return type:

Iterable(tuple(dict, str))

To get the info about the changed fields in the Context‘s purview:

from translations.context import Context
from sample.models import Continent

europe = Continent.objects.get(code='EU')

with Context(europe) as context:

    # change the instance like before
    europe.name = 'Europa'
    europe.denonym = 'Europäisch'

    # get the change fields
    changed = [info[1]
               for info in context._get_changed_fields()]

    print(changed)
[
    'Europa',
    'Europäisch',
]
create(lang=None)[source]

Create the translations of the Context‘s purview in a language.

Creates the translations using the TranslatableMeta.fields of the Context‘s purview in a language.

Parameters:

lang (str or None) – The language to create the translations in. None means use the active language code.

Raises:
  • ValueError – If the language code is not supported.

  • IntegrityError – If duplicate translations are created for a specific field of a unique instance in a language.

To create the translations of the Context‘s purview (an instance and some relations of it):

from translations.context import Context
from sample.models import Continent

europe = Continent.objects.get(code='EU')
relations = ('countries', 'countries__cities',)

with Context(europe, *relations) as context:

    # change the instance like before
    europe.name = 'Europa'
    europe.countries.all()[0].name = 'Deutschland'
    europe.countries.all()[0].cities.all()[0].name = 'Köln'

    # create the translations in German
    context.create('de')

    print('Translations created!')
Translations created!

To create the translations of the Context‘s purview (a queryset and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.all()
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # change the queryset like before
    continents[0].name = 'Europa'
    continents[0].countries.all()[0].name = 'Deutschland'
    continents[0].countries.all()[0].cities.all()[0].name = 'Köln'

    # create the translations in German
    context.create('de')

    print('Translations created!')
Translations created!

To create the translations of the Context‘s purview (a list of instances and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = list(Continent.objects.all())
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # change the list of instances like before
    continents[0].name = 'Europa'
    continents[0].countries.all()[0].name = 'Deutschland'
    continents[0].countries.all()[0].cities.all()[0].name = 'Köln'

    # create the translations in German
    context.create('de')

    print('Translations created!')
Translations created!

Note

Creating only affects the translatable fields that have changed.

If the value of a field is not changed, the translation for it is not created. (No need to set all the translatable fields beforehand)

read(lang=None)[source]

Read the translations of the Context‘s purview in a language.

Reads the translations onto the TranslatableMeta.fields of the Context‘s purview in a language.

Parameters:

lang (str or None) – The language to read the translations in. None means use the active language code.

Raises:

ValueError – If the language code is not supported.

To read the translations of the Context‘s purview (an instance and some relations of it):

from translations.context import Context
from sample.models import Continent

europe = Continent.objects.get(code='EU')
relations = ('countries', 'countries__cities',)

with Context(europe, *relations) as context:

    # read the translations in German
    context.read('de')

    # use the instance like before
    print(europe)
    print(europe.countries.all())
    print(europe.countries.all()[0].cities.all())
Europa
<TranslatableQuerySet [
    <Country: Deutschland>,
]>
<TranslatableQuerySet [
    <City: Köln>,
]>

To read the translations of the Context‘s purview (a queryset and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.all()
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # read the translations in German
    context.read('de')

    # use the queryset like before
    print(continents)
    print(continents[0].countries.all())
    print(continents[0].countries.all()[0].cities.all())
<TranslatableQuerySet [
    <Continent: Asien>,
    <Continent: Europa>,
]>
<TranslatableQuerySet [
    <Country: Deutschland>,
]>
<TranslatableQuerySet [
    <City: Köln>,
]>

To read the translations of the Context‘s purview (a list of instances and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = list(Continent.objects.all())
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # read the translations in German
    context.read('de')

    # use the list of instances like before
    print(continents)
    print(continents[0].countries.all())
    print(continents[0].countries.all()[0].cities.all())
[
    <Continent: Europa>,
    <Continent: Asien>,
]
<TranslatableQuerySet [
    <Country: Deutschland>,
]>
<TranslatableQuerySet [
    <City: Köln>,
]>

Note

Reading only affects the translatable fields that have a translation.

If there is no translation for a field, the value of the field is not changed. (It remains what it was before)

Warning

Any methods on the relations queryset which imply a database query will reset previously translated results:

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.prefetch_related(
    'countries',
)

with Context(continents, 'countries') as context:
    context.read('de')
    # querying after translation
    print(continents[0].countries.exclude(name=''))
<TranslatableQuerySet [
    <Country: Germany>,
]>

In some cases the querying can be done before the translation:

from django.db.models import Prefetch
from translations.context import Context
from sample.models import Continent, Country

# querying before translation
continents = Continent.objects.prefetch_related(
    Prefetch(
        'countries',
        queryset=Country.objects.exclude(name=''),
    ),
)

with Context(continents, 'countries') as context:
    context.read('de')
    print(continents[0].countries.all())
<TranslatableQuerySet [
    <Country: Deutschland>,
]>
update(lang=None)[source]

Update the translations of the Context‘s purview in a language.

Updates the translations using the TranslatableMeta.fields of the Context‘s purview in a language.

Parameters:

lang (str or None) – The language to update the translations in. None means use the active language code.

Raises:

ValueError – If the language code is not supported.

To update the translations of the Context‘s purview (an instance and some relations of it):

from translations.context import Context
from sample.models import Continent

europe = Continent.objects.get(code='EU')
relations = ('countries', 'countries__cities',)

with Context(europe, *relations) as context:

    # change the instance like before
    europe.name = 'Europa (changed)'
    europe.countries.all()[0].name = 'Deutschland (changed)'
    europe.countries.all()[0].cities.all()[0].name = 'Köln (changed)'

    # update the translations in German
    context.update('de')

    print('Translations updated!')
Translations updated!

To update the translations of the Context‘s purview (a queryset and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.all()
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # change the queryset like before
    continents[0].name = 'Europa (changed)'
    continents[0].countries.all()[0].name = 'Deutschland (changed)'
    continents[0].countries.all()[0].cities.all()[0].name = 'Köln (changed)'

    # update the translations in German
    context.update('de')

    print('Translations updated!')
Translations updated!

To update the translations of the Context‘s purview (a list of instances and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = list(Continent.objects.all())
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # change the list of instances like before
    continents[0].name = 'Europa (changed)'
    continents[0].countries.all()[0].name = 'Deutschland (changed)'
    continents[0].countries.all()[0].cities.all()[0].name = 'Köln (changed)'

    # update the translations in German
    context.update('de')

    print('Translations updated!')
Translations updated!

Note

Updating only affects the translatable fields that have changed.

If the value of a field is not changed, the translation for it is not updated. (No need to initialize all the translatable fields beforehand)

delete(lang=None)[source]

Delete the translations of the Context‘s purview in a language.

Deletes the translations for the TranslatableMeta.fields of the Context‘s purview in a language.

Parameters:

lang (str or None) – The language to delete the translations in. None means use the active language code.

Raises:

ValueError – If the language code is not supported.

To delete the translations of the Context‘s purview (an instance and some relations of it):

from translations.context import Context
from sample.models import Continent

europe = Continent.objects.get(code='EU')
relations = ('countries', 'countries__cities',)

with Context(europe, *relations) as context:

    # delete the translations in German
    context.delete('de')

    print('Translations deleted!')
Translations deleted!

To delete the translations of the Context‘s purview (a queryset and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.all()
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # delete the translations in German
    context.delete('de')

    print('Translations deleted!')
Translations deleted!

To delete the translations of the Context‘s purview (a list of instances and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = list(Continent.objects.all())
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # delete the translations in German
    context.delete('de')

    print('Translations deleted!')
Translations deleted!
reset()[source]

Reset the translations of the Context‘s purview to the default language.

Resets the translations on the TranslatableMeta.fields of the Context‘s purview to the default language.

To reset the translations of the Context‘s purview (an instance and some relations of it):

from translations.context import Context
from sample.models import Continent

europe = Continent.objects.get(code='EU')
relations = ('countries', 'countries__cities',)

with Context(europe, *relations) as context:

    # changes happened to the fields, create, read, update, delete, etc...
    context.read('de')

    # reset the translations
    context.reset()

    # use the instance like before
    print(europe)
    print(europe.countries.all())
    print(europe.countries.all()[0].cities.all())
Europe
<TranslatableQuerySet [
    <Country: Germany>,
]>
<TranslatableQuerySet [
    <City: Cologne>,
]>

To reset the translations of the Context‘s purview (a queryset and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = Continent.objects.all()
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # changes happened to the fields, create, read, update, delete, etc...
    context.read('de')

    # reset the translations
    context.reset()

    # use the queryset like before
    print(continents)
    print(continents[0].countries.all())
    print(continents[0].countries.all()[0].cities.all())
<TranslatableQuerySet [
    <Continent: Asia>,
    <Continent: Europe>,
]>
<TranslatableQuerySet [
    <Country: Germany>,
]>
<TranslatableQuerySet [
    <City: Cologne>,
]>

To reset the translations of the Context‘s purview (a list of instances and some relations of it):

from translations.context import Context
from sample.models import Continent

continents = list(Continent.objects.all())
relations = ('countries', 'countries__cities',)

with Context(continents, *relations) as context:

    # changes happened to the fields, create, read, update, delete, etc...
    context.read('de')

    # reset the translations
    context.reset()

    # use the list of instances like before
    print(continents)
    print(continents[0].countries.all())
    print(continents[0].countries.all()[0].cities.all())
[
    <Continent: Europe>,
    <Continent: Asia>,
]
<TranslatableQuerySet [
    <Country: Germany>,
]>
<TranslatableQuerySet [
    <City: Cologne>,
]>