From 5a4f449363a489df30f6999c36e098b8ec809ab3 Mon Sep 17 00:00:00 2001 From: Swen Kooij Date: Thu, 25 May 2017 19:23:52 +0300 Subject: [PATCH] Fix support for ArrayAgg --- localized_fields/value.py | 43 +++++++++++++++++++++++++++++++++------ tests/test_value.py | 14 ++++++++++++- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/localized_fields/value.py b/localized_fields/value.py index 6bea382..50714bc 100644 --- a/localized_fields/value.py +++ b/localized_fields/value.py @@ -1,3 +1,5 @@ +import collections + from django.conf import settings from django.utils import translation @@ -15,12 +17,7 @@ class LocalizedValue(dict): different language. """ - if isinstance(keys, str): - setattr(self, settings.LANGUAGE_CODE, keys) - else: - for lang_code, _ in settings.LANGUAGES: - value = keys.get(lang_code) if keys else None - self.set(lang_code, value) + self._interpret_value(keys); def get(self, language: str=None) -> str: """Gets the underlying value in the specified or @@ -65,6 +62,40 @@ class LocalizedValue(dict): path = 'localized_fields.fields.LocalizedValue' return path, [self.__dict__], {} + def _interpret_value(self, value): + """Interprets a value passed in the constructor as + a :see:LocalizedValue. + + If string: + Assumes it's the default language. + + If dict: + Each key is a language and the value a string + in that language. + + If list: + Recurse into to apply rules above. + + Arguments: + value: + The value to interpret. + """ + + for lang_code, _ in settings.LANGUAGES: + self.set(lang_code, None) + + if isinstance(value, str): + self.set(settings.LANGUAGE_CODE, value) + + elif isinstance(value, dict): + for lang_code, _ in settings.LANGUAGES: + lang_value = value.get(lang_code) or None + self.set(lang_code, lang_value) + + elif isinstance(value, collections.Iterable): + for val in value: + self._interpret_value(val) + def __str__(self) -> str: """Gets the value in the current language, or falls back to the primary language if there's no value diff --git a/tests/test_value.py b/tests/test_value.py index 1289ac1..7d4bd3e 100644 --- a/tests/test_value.py +++ b/tests/test_value.py @@ -33,7 +33,7 @@ class LocalizedValueTestCase(TestCase): @staticmethod def test_init_default_values(): - """Tests wehther the __init__ function + """Tests whether the __init__ function of the :see:LocalizedValue accepts the default value or an empty dict properly.""" @@ -42,6 +42,18 @@ class LocalizedValueTestCase(TestCase): for lang_code, _ in settings.LANGUAGES: assert getattr(value, lang_code) is None + @staticmethod + def test_init_array(): + """Tests whether the __init__ function + of :see:LocalizedValue properly handles an + array. + + Arrays can be passed to LocalizedValue as + a result of a ArrayAgg operation.""" + + value = LocalizedValue(['my value']) + assert value.get(settings.LANGUAGE_CODE) == 'my value' + @staticmethod def test_get_explicit(): """Tests whether the the :see:LocalizedValue