django-modeltranslation
django-modeltranslation copied to clipboard
Fallback on queryset filtering
Is it possible to apply fallback also during queries?
Suppose to have 2 languages, english and french, and to use django-modeltranslation to translate articles. Active language is french. All articles are shown in a listing page where titles are shown. Suppose titles were not translated in french, so the user sees the english title (for fallback). Suppose one of these title is 'My Christmas Holidays'. If the user now searches 'Christmas' he will find no results because the query Article.objects.filter(title__icontains = 'Christmas') will find no results if the french title is not set, since fallback is not applied here.
This is strange for the user, since he saw there was at least one article with "Christmas".
So, is there a way to make fallback work also on querysets? Thanks.
The first thought is "yes". It would need to rewrite .filter(title__icontains = 'Christmas')
into .filter(Q(title_fr__icontains = 'Christmas') | Q(title_fr='', title_en__icontains = 'Christmas'))
I just ran into the same issue. Here the symptom is an admin listing filter triggering different results depending on the locale. Having researched the issue further, it boils down to modeltranslation not doing language fallback on query filter criteria.
@zlorf I'm not sure if your response meant that you'd be interested in having that in modeltranslation itself or if we should adapt our code instead? If you think this feature could make its way to modeltranslation, I can try to come up with a patch.
@amarandon Yes, I think this should come to modeltranslation. I've already designed a patch in my mind, but I have little time to actually write it down. :( Comming (not very) soon.
I’m adding my voice to this.
I ran into this kind of issue while trying to integrate modeltranslation into mezzanine/cartridge. In the end, I have something along the lines of (given a ProductOption
p
):
option = ProductOption.objects.get(type=p.type, name=p.name)
raising a DoesNotExist
exception if name is not defined in the current language (and thus p.name
falls back).
The patch will be greatly appreciated.
Just hit this one myself when using .get(slug='myslug')
with a non-default language. Ideally it should be able to fallback.
Has anyone made any progress on this?
Still open after 5.5 years :rofl:
I took a quick look at the code and it seems there're a lot of things to handle (filter/exclude, Q/F, order…).
2 ideas to provide a useful "if translated empty use raw" functionality (title_fr__icontains='foo' OR (title_fr='' AND title__icontains='foo')
); not very clean but better than nothing?
- Detect filter on only
slug_field
(cf.DetailView
CBV). - Provide specific methods (
multilingual_filter|exclude
) that rewrites all fields to "translated or raw".
Instead of using raw value, this could handle fallback languages.