doniyor
doniyor

Reputation: 37904

django model translation - filter by translated field

I need to query like:

MyModel.objects.filter(title_de="some title")

where de inside title_de is dynamic

I cannot do:

MyModel.objects.filter('title_%s' % language = "some title")

how can I do this?

Upvotes: 2

Views: 2328

Answers (2)

petkostas
petkostas

Reputation: 7460

Use kwargs,

kwargs = {
    f"title_{language}": "some title"
}
MyModel.objects.filter(**kwargs)

Upvotes: 8

steps
steps

Reputation: 638

If, in your example, language is the current language, then this will work out of the box. See the modeltranslation docs:

It works as follow: if the translation field name is used (title), it is changed into the current language field name (title_de or title_en, depending on the current active language). Any language-suffixed names are left untouched (so title_en wouldn’t change, no matter what the current language is).

There is no fallback in case there is no translation available for the given language (see e.g. this question), so this has the same effect as specifically querying a language-specific field.

Upvotes: 2

Related Questions