Access django translated fields in values

51 views Asked by At

I have a model with translate fields

class Certificate(TranslatableModel, BaseModel):
    enabled = models.BooleanField(default=True)
    translations = TranslatedFields(
        certificate_name=models.CharField(max_length=255, blank=True, default=""),
        description=models.CharField(max_length=400, blank=True, default=""),
    )
    type = models.CharField(max_length=30, null=False, blank=False)

When I attempt to query it and get the certificate_name in .values():

certificates_values_list = (
    Certificate.objects.filter(
        enabled=True
    )
    .values(
        "id",
        "type",
        "certificate_name",
    )
)

It returns an error that the certificate_name is not exists for the certificated model. I also tried:

certificates_values_list = (
    Certificate.objects.filter(
        enabled=True
    )
    .values(
        "id",
        "type",
        "translations__certificate_name",
    )
)

But it returns duplicated instances one for each available translation so that the same certificate id got duplicated twice/thrice based on the available translation.

What I need is to get only the objects with the translated fields according to the current language and the fallback if no objects related to the current language. How can I implement this?

1

There are 1 answers

0
42WaysToAnswerThat On

This page has a throughout tutorial that contains the answer to your question: https://pypi.org/project/django-parler/

Quoting a section of the tutorial:

Filtering translations

To query translated fields, use the .translated() method:

MyObject.objects.translated(title='cheese omelet')

To access objects in both the current and possibly the fallback language, use:

MyObject.objects.active_translations(title='cheese omelet')

This returns objects in the languages which are considered “active”, which are:

- The current language

- The fallback language when hide_untranslated=False in the PARLER_LANGUAGES setting.