Given a Django model with a JSONField, what is the correct way of serializing and deserializing it using Django Rest Framework?
I've already tried crating a custom serializers.WritableField
and overriding to_native
and from_native
:
from json_field.fields import JSONEncoder, JSONDecoder
from rest_framework import serializers
class JSONFieldSerializer(serializers.WritableField):
def to_native(self, obj):
return json.dumps(obj, cls = JSONEncoder)
def from_native(self, data):
return json.loads(data, cls = JSONDecoder)
But when I try to updating the model using partial=True
, all the floats in the JSONField objects become strings.
For the record, this "just works" now if you are using PostgreSQL, and your model field is a
django.contrib.postgres.JSONField
.I'm on PostgreSQL 9.4, Django 1.9, and Django REST Framework 3.3.2.
I have previously used several of the other solutions listed here, but was able to delete that extra code.
Example Model:
Example Serializer:
Example View:
If you're using mysql (haven't tried with other databases), using both DRF's new
JSONField
and Mark Chackerian's suggestedJSONSerializerField
will save the json as a{u'foo': u'bar'}
string. If you rather save it as{"foo": "bar"}
, this works for me:Mark Chackerian script didn't work for me, I'd to force the json transform:
Works fine. Using DRF 3.15 and JSONFields in Django 1.8
If you're using Django Rest Framework >= 3.3, then the JSONField serializer is now included. This is now the correct way.
If you're using Django Rest Framework < 3.0, then see gzerone's answer.
If you're using DRF 3.0 - 3.2 AND you can't upgrade AND you don't need to serialize binary data, then follow these instructions.
First declare a field class:
And then add in the field into the model like
And, if you do need to serialize binary data, you can always the copy official release code
If and only if you know the first-level style of your JSON content (List or Dict), you can use DRF builtin DictField or ListField.
Ex:
It works fine, with
GET/PUT/PATCH/POST
, including with nested contents.