Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support polymorphic objects #193

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion jsonfield/fields.py
Expand Up @@ -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', {})
Expand Down Expand Up @@ -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)
Expand Down
25 changes: 25 additions & 0 deletions jsonfield/tests.py
Expand Up @@ -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)