Reference: Utilities

This module contains the utilities 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.

translations.utils._get_reverse_relation(model, relation)[source]

Return the reverse of a model’s relation.

Processes the model’s relation which points from the model to the target model and returns the reverse relation which points from the target model back to the model.

Parameters
  • model (type(Model)) – The model which contains the relation and the reverse relation points to.

  • relation (str) – The relation of the model to get the reverse of. It may be divided into separate parts by LOOKUP_SEP (usually __) to represent a deeply nested relation. Each part must be a related_query_name.

Returns

The reverse of the model’s relation.

Return type

str

Raises

FieldDoesNotExist – If the relation is pointing to the fields that don’t exist.

To get the reverse of a model’s relation:

from translations.utils import _get_reverse_relation
from sample.models import Continent

# get the reverse relation
reverse_relation = _get_reverse_relation(Continent,
                                         'countries__cities')

print('City can be queried with `{}`'.format(reverse_relation))
City can be queried with `country__continent`
translations.utils._get_dissected_lookup(model, lookup)[source]

Return the dissected info of a lookup.

Dissects the lookup and returns comprehensive information about it, like what relations does it follow, what field name and supplementary lookup does it contain and whether the field is translatable or not.

Parameters
  • model (type(Model)) – The model which the lookup acts on.

  • lookup (str) – The lookup of the model to get the dissected info of. It may be divided into separate parts by LOOKUP_SEP (usually __) to represent a deeply nested relation. Each part must be a related_query_name.

Returns

The dissected info of the lookup.

Return type

dict

Raises

To get the dissected info of a lookup:

from translations.utils import _get_dissected_lookup
from sample.models import Continent

# get the dissected lookup
info = _get_dissected_lookup(Continent,
                             'countries__name__icontains')

print(info)
{
    'field': 'name',
    'relation': [
        'countries',
    ],
    'supplement': 'icontains',
    'translatable': True,
}
translations.utils._get_relations_hierarchy(*relations)[source]

Return the relations hierarchy of some relations.

Transforms the relations into a relations hierarchy. Each level of relations hierarchy contains the relations in that level and each relation contains certain information, things like whether the relation is included or not and what are its nested relations, forming the next level of relations hierarchy.

Parameters

relations (list(str)) – The relations to get the relations hierarchy of. Each relation may be divided into separate parts by LOOKUP_SEP (usually __) to represent a deeply nested relation.

Returns

The relations hierarchy of the relations.

Return type

dict(str, dict)

To get the relations hierarchy of some relations (a first-level relation):

from translations.utils import _get_relations_hierarchy

# get the relations hierarchy
hierarchy = _get_relations_hierarchy('countries')

print(hierarchy)
{
    'countries': {
        'included': True,
        'relations': {},
    },
}

To get the relations hierarchy of some relations (a second-level relation not including the first-level relation):

from translations.utils import _get_relations_hierarchy

# get the relations hierarchy
hierarchy = _get_relations_hierarchy('countries__cities')

print(hierarchy)
{
    'countries': {
        'included': False,
        'relations': {
            'cities': {
                'included': True,
                'relations': {},
            },
        },
    },
}

To get the relations hierarchy of some relations (a second-level relation including the first-level relation):

from translations.utils import _get_relations_hierarchy

# get the relations hierarchy
hierarchy = _get_relations_hierarchy('countries',
                                     'countries__cities')

print(hierarchy)
{
    'countries': {
        'included': True,
        'relations': {
            'cities': {
                'included': True,
                'relations': {},
            },
        },
    },
}

To get the relations hierarchy of some relations (no relations):

from translations.utils import _get_relations_hierarchy

# get the relations hierarchy
hierarchy = _get_relations_hierarchy()

print(hierarchy)
{}
translations.utils._get_entity_details(entity)[source]

Return the iteration and type details of an entity.

If the entity is an iterable it returns the entity as iterable and the type of the first object in the iteration (since it assumes all the objects in the iteration are of the same type), otherwise it returns the entity as not iterable and the type of the entity.

Parameters

entity (Model or Iterable(Model)) – The entity to get the details of.

Returns

The details of the entity as (iterable, model).

Return type

tuple(bool, type(Model))

Raises

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

Note

If the entity is an empty iterable it returns the model as None, even if the iterable is an empty queryset (which the model of can be retrieved).

To get the iteration and type details of an entity (a list of instances):

from translations.utils import _get_entity_details
from sample.models import Continent

continents = list(Continent.objects.all())

# get the entity details
details = _get_entity_details(continents)

print('Iterable: {}'.format(details[0]))
print('Model: {}'.format(details[1]))
Iterable: True
Model: <class 'sample.models.Continent'>

To get the iteration and type details of an entity (a queryset):

from translations.utils import _get_entity_details
from sample.models import Continent

continents = Continent.objects.all()

# get the entity details
details = _get_entity_details(continents)

print('Iterable: {}'.format(details[0]))
print('Model: {}'.format(details[1]))
Iterable: True
Model: <class 'sample.models.Continent'>

To get the iteration and type details of an entity (an instance):

from translations.utils import _get_entity_details
from sample.models import Continent

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

# get the entity details
details = _get_entity_details(europe)

print('Iterable: {}'.format(details[0]))
print('Model: {}'.format(details[1]))
Iterable: False
Model: <class 'sample.models.Continent'>

To get the iteration and type details of an entity (an empty list):

from translations.utils import _get_entity_details
from sample.models import Continent

empty = []

# get the entity details
details = _get_entity_details(empty)

print('Iterable: {}'.format(details[0]))
print('Model: {}'.format(details[1]))
Iterable: True
Model: None
translations.utils._get_purview(entity, hierarchy)[source]

Return the purview of an entity and a relations hierarchy of it.

Returns the mapping of the instances specified by the entity and its relations, and the query to fetch their translations.

Parameters
  • entity (Model or Iterable(Model)) – the entity to get the purview of.

  • hierarchy (dict(str, dict)) – The relations hierarchy of the entity to get the purview of. Each relation in the hierarchy must be a related_name.

Returns

The purview of the entity and the relations hierarchy of it.

Return type

tuple(dict(int, dict(str, Model)), Q)

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 get the purview of an entity and a relations hierarchy of it:

from django.contrib.contenttypes.models import ContentType
from translations.utils import _get_relations_hierarchy, _get_purview
from sample.models import Continent, Country, City

def ct(obj):
    return ContentType.objects.get_for_model(type(obj)).id

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

# get the purview
mapping, query = _get_purview(continents, hierarchy)

europe = continents[0]
germany = europe.countries.all()[0]
cologne = germany.cities.all()[0]

print(mapping[ct(europe)][str(europe.pk)] is europe)
print(mapping[ct(germany)][str(germany.pk)] is germany)
print(mapping[ct(cologne)][str(cologne.id)] is cologne)
True
True
True
translations.utils._get_translations(query, lang)[source]

Return the Translation queryset of a query in a language.

Queries the Translation model using the provided query in the specified language and returns the queryset.

Parameters
Returns

The Translation queryset of the query in the language.

Return type

QuerySet(Translation)

To get the Translation queryset of a query in a language:

from translations.utils import _get_relations_hierarchy, _get_purview, _get_translations
from sample.models import Continent

continents = list(Continent.objects.all())
hierarchy = _get_relations_hierarchy('countries',
                                     'countries__cities',)
mapping, query = _get_purview(continents, hierarchy)

# get the translations
translations = _get_translations(query, 'de')

print(translations)
<QuerySet [
    <Translation: Europe: Europa>,
    <Translation: European: Europäisch>,
    <Translation: Germany: Deutschland>,
    <Translation: German: Deutsche>,
    <Translation: Cologne: Köln>,
    <Translation: Cologner: Kölner>,
    <Translation: Asia: Asien>,
    <Translation: Asian: Asiatisch>,
    <Translation: South Korea: Südkorea>,
    <Translation: South Korean: Südkoreanisch>,
    <Translation: Seoul: Seül>,
    <Translation: Seouler: Seüler>,
]>