diff --git a/jsonfield/fields.py b/jsonfield/fields.py index 21a6e23..f5a6d02 100644 --- a/jsonfield/fields.py +++ b/jsonfield/fields.py @@ -21,6 +21,13 @@ from .encoder import JSONEncoder +def polymorphic_has_pk(obj): + if getattr(obj, 'polymorphic_primary_key_name', None): + if getattr(obj, obj.polymorphic_primary_key_name, None): + return True + return False + + class JSONFormFieldBase(object): def __init__(self, *args, **kwargs): self.load_kwargs = kwargs.pop('load_kwargs', {}) @@ -77,7 +84,9 @@ def pre_init(self, value, obj): # Make sure the primary key actually exists on the object before # checking if it's empty. This is a special case for South datamigrations # see: https://github.com/bradjasper/django-jsonfield/issues/52 - if getattr(obj, "pk", None) is not None: + # Check if its a polymorphic objects and has a primary key + # see: https://github.com/dmkoch/django-jsonfield/issues/101 + if getattr(obj, "pk", None) is not None or polymorphic_has_pk(obj): if isinstance(value, six.string_types): try: return json.loads(value, **self.load_kwargs) diff --git a/jsonfield/tests.py b/jsonfield/tests.py index 2d0b980..950cea9 100644 --- a/jsonfield/tests.py +++ b/jsonfield/tests.py @@ -390,3 +390,28 @@ def test_get_prep_value_can_return_none_if_null(self): self.assertDictEqual(value, json.loads(json.loads(double_prepared_value))) self.assertIs(json_field_instance.get_prep_value(None), None) + + +class JsonModelWithCustomPrimaryKey(models.Model): + my_key = models.PositiveIntegerField(primary_key=True) + json = JSONField() + default_json = JSONField(default={"check": 12}) + complex_default_json = JSONField(default=[{"checkcheck": 1212}]) + empty_default = JSONField(default={}) + + +class JSONFieldWithCustomPrimaryKeyTest(TestCase): + """Tests objects with custom primary key""" + + json_model = JsonModelWithCustomPrimaryKey + + def test_json_field_create(self): + """Test saving a JSON object in our JSONField on an object with custom pk""" + json_obj = { + "item_1": "this is a json blah", + "blergh": "hey, hey, hey"} + + obj = self.json_model.objects.create(json=json_obj, my_key=1) + new_obj = self.json_model.objects.get(pk=obj.pk) + + self.assertEqual(new_obj.json, json_obj)