rpkilby / jsonfield

A reusable Django model field for storing ad-hoc JSON data
MIT License
1.16k stars 271 forks source link

Django Serialization + Deserialisation results in invalid data #216

Closed AnnaDamm closed 4 years ago

AnnaDamm commented 6 years ago

Description

  1. Have a model with the json field

  2. Add an instance to the database with a json object inside the json field, like {"foo": "bar"}

  3. serialize using django's serializer:

    from django.core import serializers data = serializers.serialize("python", SomeModel.objects.all())

  4. deserialize again

    serializers.deserialize("python", data)

Behaviour The deserialized model has the data encoded as a string, not an actual dict, like "{\"foo\": \"bar\"}"

Expected Behaviour The data in the field is actually a dict

agfunder commented 6 years ago

I had exactly this problem.

This fixed it:

pip uninstall django-jsonfield pip install jsonfield

(I still had to repair my stringified json field data).

nosenka commented 5 years ago

I have a same issue. Looks like this happens only when model instance has no primary key.

I tried to make a fixtures for a model, which contains a JSONField. So, if i provide a pk for model - everything is fine. But when I remove a primary key (I wish to use natural_key instead) - manage.py loaddata writes a broken json string into a database, like "{\"foo\":\"bar\"}" (include double-quotes).

This issue can be simply reproduced: obj = Model(some_json_field='{"foo":"bar"}') obj.some_json_field

An output will be (string, not dict):

'{"foo":"bar"}'

But if model instance has a primary key - field will contain a dict: obj = Model(id=123, some_json_field='{"foo":"bar"}') obj.some_json_field

{'foo': 'bar'}

rpkilby commented 4 years ago

Hi all. I've added tests that ensure instances (saved or unsaved) can be serialized then deserialized.