From 59db2268d0cdfecd0c621f17f954ea56f477527f Mon Sep 17 00:00:00 2001 From: Ryan P Kilby Date: Tue, 5 Dec 2017 00:52:17 -0500 Subject: [PATCH] Ensure 'HStoreField' child is a 'CharField' --- rest_framework/fields.py | 7 +++++++ tests/test_fields.py | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index b39f394f6..a2b968168 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1687,6 +1687,13 @@ class DictField(Field): class HStoreField(DictField): child = CharField(allow_blank=True, allow_null=True) + def __init__(self, *args, **kwargs): + super(HStoreField, self).__init__(*args, **kwargs) + assert isinstance(self.child, CharField), ( + "The `child` argument must be an instance of `CharField`, " + "as the hstore extension stores values as strings." + ) + class JSONField(Field): default_error_messages = { diff --git a/tests/test_fields.py b/tests/test_fields.py index 88bf21678..3ff230e66 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1913,6 +1913,15 @@ class TestHStoreField(FieldValues): ] field = serializers.HStoreField() + def test_child_is_charfield(self): + with pytest.raises(AssertionError) as exc_info: + serializers.HStoreField(child=serializers.IntegerField()) + + assert str(exc_info.value) == ( + "The `child` argument must be an instance of `CharField`, " + "as the hstore extension stores values as strings." + ) + def test_no_source_on_child(self): with pytest.raises(AssertionError) as exc_info: serializers.HStoreField(child=serializers.CharField(source='other'))