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.
If you want JSONField for mysql this is done in django-mysql and serializer was fixed some day ago [1], is not yet in any release.
[1] https://github.com/adamchainz/django-mysql/issues/353
setting.py
add:
models.py
Thanks by the help. This is the code i finally use for render it
serializers.WritableField is deprecated. This works:
In 2.4.x: