2

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?

doniyor
  • 36,596
  • 57
  • 175
  • 260

2 Answers2

8

Use kwargs,

kwargs = {
    f"title_{language}": "some title"
}
MyModel.objects.filter(**kwargs)
silox
  • 43
  • 9
petkostas
  • 7,250
  • 3
  • 26
  • 29
2

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.

Community
  • 1
  • 1
steps
  • 618
  • 1
  • 7
  • 18