Django modeltranslation queries fallback

别说谁变了你拦得住时间么 提交于 2019-12-31 01:43:38

问题


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

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".

How can I make this work?

Thanks in advance.


回答1:


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

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

I hope it helps!




回答2:


You must ensure that your model is registered in translation.py

from modeltranslation.translator import register, TranslationOptions
@register(YourModel)
class YourModel(TranslationOptions):
    pass

In this way all the queries that are done will return the appropriate field depending on the language in which it is, this because to register it is created a MultilingualManager



来源:https://stackoverflow.com/questions/27418377/django-modeltranslation-queries-fallback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!