简体   繁体   English

django模型翻译-按翻译字段过滤

[英]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 其中, detitle_de是动态

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. 在您的示例中,如果language是当前语言,那么它将立即可用。 See the modeltranslation docs : 请参阅modeltranslation文档

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). 它的工作原理如下:当翻译领域名称是用来( title ),将其改变为当前语言字段名( title_detitle_en ,根据当前活跃的语言)。 Any language-suffixed names are left untouched (so title_en wouldn't change, no matter what the current language is). 任何带有语言后缀的名称都将保持不变(因此无论当前语言是什么, title_en都不会改变)。

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. 如果没有针对给定语言的翻译,就不会有退路(例如,请参见此问题 ),因此,这与专门查询特定于语言的字段具有相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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