I have an app that supports internationalization, and I designed the models as follows:
class EventType(models.Model):
icon = models.CharField(_("Icon"), max_length=50, null=True, blank=True, help_text=_("Event type icon, can be found at https://tabler.io/icons"))
color = models.CharField(_("Color"), max_length=50, null=True, blank=True, help_text=_("Event type color, can be found at https://getbootstrap.com/docs/4.0/utilities/colors/"))
created_at = models.DateTimeField(_("Created at"), auto_now_add=True)
updated_at = models.DateTimeField(_("Updated at"), auto_now=True)
class Meta:
verbose_name = _("Event Type")
verbose_name_plural = _("Event Types")
def get_translation(self):
"""Returns the translated name for the current language or a fallback"""
language_code = get_language()
translation = next((t for t in self.translations.filter(language__code=language_code)), None)
return translation.name if translation else _("No name")
def __str__(self):
return self.get_translation()
class EventTypeTranslation(models.Model):
event_type = models.ForeignKey(EventType, on_delete=models.CASCADE, related_name="translations", verbose_name=_("Event Type"))
language = models.ForeignKey(Language, on_delete=models.CASCADE, verbose_name=_("Language"))
name = models.CharField(_("Name"), max_length=100)
description = RichTextField(_("Description"), null=True, blank=True)
created_at = models.DateTimeField(_("Created at"), auto_now_add=True)
updated_at = models.DateTimeField(_("Updated at"), auto_now=True)
class Meta:
verbose_name = _("Event Type Translation")
verbose_name_plural = _("Event Type Translations")
def __str__(self):
return self.name
However, the queries in the Django admin are very slow due to the get_translation
method.
Does anyone have a suggestion for how I can make the __str__
method return the translated name in a more performant way?