Allow raw dicts to be used in update statements

This commit is contained in:
Swen Kooij 2018-03-31 16:53:10 +03:00
parent 8fbe3e8680
commit ccc46e1899
2 changed files with 52 additions and 0 deletions

View File

@ -131,6 +131,8 @@ class LocalizedField(HStoreField):
specified, we'll treat it as an empty :see:LocalizedValue specified, we'll treat it as an empty :see:LocalizedValue
instance, on which the validation will fail. instance, on which the validation will fail.
Dictonaries are converted into :see:LocalizedValue instances.
Arguments: Arguments:
value: value:
The :see:LocalizedValue instance to serialize The :see:LocalizedValue instance to serialize
@ -141,6 +143,9 @@ class LocalizedField(HStoreField):
extracted from the specified value. extracted from the specified value.
""" """
if isinstance(value, dict):
value = LocalizedValue(value)
# default to None if this is an unknown type # default to None if this is an unknown type
if not isinstance(value, LocalizedValue) and value: if not isinstance(value, LocalizedValue) and value:
value = None value = None

47
tests/test_query_set.py Normal file
View File

@ -0,0 +1,47 @@
from django.conf import settings
from django.test import TestCase
from django.utils import translation
from localized_fields.fields import LocalizedField
from .fake_model import get_fake_model
class LocalizedQuerySetTestCase(TestCase):
"""Tests query sets with models containing :see:LocalizedField."""
Model = None
@classmethod
def setUpClass(cls):
"""Creates the test models in the database."""
super(LocalizedQuerySetTestCase, cls).setUpClass()
cls.Model = get_fake_model(
{
'title': LocalizedField(),
}
)
@classmethod
def test_assign_raw_dict(cls):
inst = cls.Model()
inst.title = dict(en='Bread', ro='Paine')
inst.save()
inst = cls.Model.objects.get(pk=inst.pk)
assert inst.title.en == 'Bread'
assert inst.title.ro == 'Paine'
@classmethod
def test_assign_raw_dict_update(cls):
inst = cls.Model.objects.create(
title=dict(en='Bread', ro='Paine'))
cls.Model.objects.update(
title=dict(en='Beer', ro='Bere'))
inst = cls.Model.objects.get(pk=inst.pk)
assert inst.title.en == 'Beer'
assert inst.title.ro == 'Bere'