Fix support for ArrayAgg

This commit is contained in:
Swen Kooij
2017-05-25 19:23:52 +03:00
parent 0fa79ddbb0
commit 5a4f449363
2 changed files with 50 additions and 7 deletions

View File

@@ -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