Added the default parameter to the get_multi_lingual_attr() function to allow a different default lanugage for a data model.

This commit is contained in:
依瑪貓 2020-07-16 23:18:16 +08:00
parent 418dcd9803
commit e2945045f3
2 changed files with 9 additions and 3 deletions

View File

@ -55,7 +55,7 @@ class Country(models.Model):
@property @property
def name(self): def name(self):
if self._name is None: if self._name is None:
self._name = get_multi_lingual_attr(self, "name") self._name = get_multi_lingual_attr(self, "name", "en")
return self._name return self._name
@name.setter @name.setter

View File

@ -32,15 +32,18 @@ class Language:
language (str): The Django language code. language (str): The Django language code.
Attributes: Attributes:
id (str): The language ID
db (str): The database column suffix of this language. db (str): The database column suffix of this language.
locale (str); The locale name of this language. locale (str); The locale name of this language.
is_default (bool): Whether this is the default language. is_default (bool): Whether this is the default language.
""" """
id = None
db = None db = None
locale = None locale = None
is_default = False is_default = False
def __init__(self, language): def __init__(self, language):
self.id = language
self.db = "_" + language.lower().replace("-", "_") self.db = "_" + language.lower().replace("-", "_")
if language == "zh-hant": if language == "zh-hant":
self.locale = "zh-TW" self.locale = "zh-TW"
@ -59,12 +62,13 @@ class Language:
return Language(get_language()) return Language(get_language())
def get_multi_lingual_attr(model, name): def get_multi_lingual_attr(model, name, default=None):
"""Returns a multi-lingual attribute of a data model. """Returns a multi-lingual attribute of a data model.
Args: Args:
model (object): The data model. model (object): The data model.
name (str): The attribute name. name (str): The attribute name.
default (str): The default language.
Returns: Returns:
(any): The attribute in this language, or in the default (any): The attribute in this language, or in the default
@ -72,7 +76,9 @@ def get_multi_lingual_attr(model, name):
""" """
language = Language.current() language = Language.current()
title = getattr(model, name + language.db) title = getattr(model, name + language.db)
if language.is_default: if default is None:
default = Language.default().id
if language.id == default:
return title return title
if title is not None: if title is not None:
return title return title