SectorLabs/django-localized-fields

Add a fallback mechanism

umazalakain opened this issue · 3 comments

Right now LocalizedValue falls back to the primary language if no translation for the current language is present. I think it's interesting if the user could specify a fallback chain. This could be in a per-missing-language fashion:

LOCALIZED_FIELDS_FALLBACKS = {
    'en': ['es', 'eu'],
    'es': ['eu', 'en'],
    'eu': ['es', 'en'],
}

For backwards compatibility, LOCALIZED_FIELDS_FALLBACKS.get(lang, [PRIMARY_LANGUAGE]).

Alternatively, the setting could be a function that is given the missing language and field info.

This could be a global setting or a field parameter.

Definitely an interesting idea! I'd like to se this. If I have some time on my hands, I'll add this :)

I've added basic support for this. I could not implement this into the get method without breaking backwards compatibility.

However, casting the LocalizedValue to a string (str(myvalue)) now utilizes the fallback setting. The default behavior (not having LOCALIZED_FIELDS_FALLBACKS) did not change.

Suppose we have a function that needs to get all the values in Spanish, but wants to fall back to Portuguese in case Spanish is not available:

LOCALIZED_FIELDS_FALLBACKS = {
      'es': ['pt']
}

with translation.override('es'):
      value = str(mymodel.name) # will return portugese if spanish is not available

I'll release a new version of the package within a few hours :)

How nice! Thanks!