Created
August 22, 2011 16:35
-
-
Save armonge/1162845 to your computer and use it in GitHub Desktop.
A model Mixin to use in translatable applications, to use inherit your models from this
This file contains hidden or 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
class TranslatableModelMixin(models.Model): | |
''' | |
Adapted from http://snippets.dzone.com/posts/show/2979 | |
''' | |
language = models.CharField(max_length=2, choices=settings.LANGUAGES, db_index=True) | |
translation_of = models.ForeignKey( | |
to='self', | |
related_name='translation_set', | |
limit_choices_to={'language' : settings.DEFAULT_LANGUAGE}, | |
blank=True, | |
null=True, | |
) | |
def get_root_translation(self): | |
"""Returns the root translation for this page. | |
This page will be in the settings.DEFAULT_LANGUAGE.""" | |
if self.translation_of is None: | |
return self | |
else: | |
return self.translation_of | |
def get_translations(self): | |
"""Return all of the translations for this page.""" | |
# If I am the root translation, just return all of my translations. | |
if self.translation_of is None: | |
return self.translation_set.all() | |
else: | |
# If I am not the root, return the root translations, plus all of its | |
# translations, minus myself. | |
return self.__class__().objects.filter( | |
Q(pk=self.translation_of.pk) | | |
Q(translation_of=self.translation_of.pk)).exclude(pk = self.pk) | |
def get_translation(self, language): | |
"""Return a specific translation of this page.""" | |
if self.language == language: | |
return self | |
# If I am the root translation, search for translations of me in the given language | |
elif self.translation_of is None: | |
try: | |
return self.translation_set.get(translation_of=self.id, language=language) | |
except self.DoesNotExist: | |
return None | |
# Find the root page and the specific translation | |
else: | |
# If am not the root, find the root page with the given language, | |
# otherwise find the page that is a translation of me in the given language | |
return TranslatableModelMixin.objects.filter( | |
models.Q(id=self.translation_of.id) | | |
models.Q(translation_of=self.translation_of.id), | |
language=language) | |
class Meta: | |
abstract = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment