Created
December 4, 2012 13:30
-
-
Save alesdotio/4203873 to your computer and use it in GitHub Desktop.
lazy translation getter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def lazy_translation_getter(self, name, default=None): | |
""" | |
Lazy translation getter that fetches translations from DB in case the instance is currently untranslated and | |
saves the translation instance in the translation cache | |
""" | |
stuff = self.safe_translation_getter(name, NoTranslation) | |
if stuff is not NoTranslation: | |
return stuff | |
# get all translations | |
translations = self._meta.translations_model.objects.filter(master__pk=self.pk) | |
# make them a nice dict | |
translation_dict = {} | |
for translation in translations: | |
translation_dict[translation.language_code] = translation | |
# see if we have the right language | |
correct_language = translation_dict.get(get_language()) | |
if correct_language: | |
# CACHE IT! | |
setattr(self, self._meta.translations_cache, correct_language) | |
return getattr(correct_language, name, default) | |
# otherwise just get any language (really?) | |
try: | |
any_language = translation_dict.values()[0] | |
except IndexError: | |
return default | |
# cache it (really?) | |
setattr(self, self._meta.translations_cache, any_language) | |
return getattr(any_language, name, default) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment