From fc80462ce7af59b6ade008471d5da73b4d9c0966 Mon Sep 17 00:00:00 2001 From: seroy Date: Thu, 13 Apr 2017 11:41:24 +0300 Subject: [PATCH 1/2] added test for str parameter to_python method --- tests/test_localized_field.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/test_localized_field.py b/tests/test_localized_field.py index 45d657f..7495770 100644 --- a/tests/test_localized_field.py +++ b/tests/test_localized_field.py @@ -1,3 +1,4 @@ +import json from django.conf import settings from django.db.utils import IntegrityError from django.test import TestCase @@ -232,6 +233,20 @@ class LocalizedFieldTestCase(TestCase): for lang_code, _ in settings.LANGUAGES: assert localized_value.get(lang_code) is None + @staticmethod + def test_to_python_str(): + """Tests whether the :see:to_python function produces + the expected :see:LocalizedValue when it is + passed serialized string value.""" + + serialized_str = json.dumps(get_init_values()) + localized_value = LocalizedField().to_python(serialized_str) + assert isinstance(localized_value, LocalizedValue) + + for language, value in get_init_values().items(): + assert localized_value.get(language) == value + assert getattr(localized_value, language) == value + @staticmethod def test_get_prep_value(): """"Tests whether the :see:get_prep_value function From f1798b0cc6680aaa8ed5821cd9ab6e8cbc3cec04 Mon Sep 17 00:00:00 2001 From: seroy Date: Thu, 13 Apr 2017 11:53:56 +0300 Subject: [PATCH 2/2] added ability to deserialize string value --- localized_fields/fields/localized_field.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/localized_fields/fields/localized_field.py b/localized_fields/fields/localized_field.py index 1f3d205..8798892 100644 --- a/localized_fields/fields/localized_field.py +++ b/localized_fields/fields/localized_field.py @@ -1,3 +1,5 @@ +from typing import Union + from django.conf import settings from django.db.utils import IntegrityError from django.utils import six, translation @@ -114,7 +116,7 @@ class LocalizedField(HStoreField): return cls.attr_class(value) - def to_python(self, value: dict) -> LocalizedValue: + def to_python(self, value: Union[dict, str, None]) -> LocalizedValue: """Turns the specified database value into its Python equivalent. @@ -127,7 +129,8 @@ class LocalizedField(HStoreField): A :see:LocalizedValue instance containing the data extracted from the database. """ - + # make deserialization if need by parent method + value = super(LocalizedField, self).to_python(value) if not value or not isinstance(value, dict): return self.attr_class()