Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

python - Django modeltranslation queries fallback

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...