简体   繁体   中英

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?

Use kwargs,

kwargs = {}
title_arg = 'title_%s' % language
kwargs[title_arg] = "some title"

MyModel.objects.filter(**kwargs)

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 eg this question ), so this has the same effect as specifically querying a language-specific field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM