Django model fallback

I am using django modeltranslation for a multilingual site.

Language fallback works when reading attributes directly. For example, if the current language is German and I print object.title, if no German title is defined, I will see the title in the English version.

I would expect rollback to work on requests as well, but it doesn't. In fact, if I do something like

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

      

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

How can I make this work?

Thanks in advance.

+3


source to share


2 answers


The language of desire must be explicitly requested here. 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 does this work? Because when you ask for a specific language, ModelTranslation stores it. Otherwise, it uses the current language.

Hope this helps!

0


source


You have to make sure your model is registered in translation.py

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

      



Thus, all executed queries return the corresponding field depending on the language in which it is located, because MultilingualManager was created for registration

0


source







All Articles