Django modeltranslation查询回退 [英] Django modeltranslation queries fallback

查看:138
本文介绍了Django modeltranslation查询回退的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多语言网站中使用django modeltranslation。

I'm using django modeltranslation for a multi-language site.

语言后备在直接读取属性时工作良好。
例如,如果当前语言是德语,我打印object.title,如果没有定义德语标题,我将看到英文标题。

Language fallback works good when reading attributes directly. For example, if current language is German and I print object.title, if the German title is not defined I'll see the english title.

我期望回退也可以在查询上工作,但这不是真的。
事实上,如果我执行类似

I would expect fallback to work also on queries, but that's not true. In fact, if i do something like

results = MyModel.objects.filter(title = 'hello')

如果没有设置德语标题,这将不会得到结果,而我希望它返回

this will get no results if the German title is not set, while I would like it to return the object with english title "hello".

如何使这项工作?

提前感谢。 / p>

Thanks in advance.

推荐答案

这里要做的是明确地查询欲望语言。在你的情况下:

The thing to do here is to explicitly query the desire language. In your case:

from django.db.models import Q
# ...
# define your query like this: 
results = MyModel.objects.filter(Q(title_de = 'hello') | Q(title_en = 'hello'))
# supposing you have German and English languages set

为什么这个工作?因为当您查询特定语言时,ModelTranslation保留它。否则它会使用当前的语言。

Why this work? Because when you query the specific language, ModelTranslation keep it. Otherwise it use the current language.

我希望它有帮助!

这篇关于Django modeltranslation查询回退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆