python - Django Rest Framework and JSONField -


given django model jsonfield, correct way of serializing , deserializing using django rest framework?

i've tried crating custom serializers.writablefield , overriding to_native , from_native:

from json_field.fields import jsonencoder, jsondecoder 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 try updating model using partial=true, floats in jsonfield objects become strings.

if you're using django rest framework >= 3.3, jsonfield serializer now included. correct way.

if you're using django rest framework < 3.0, see gzerone's answer.

if you're using drf 3.0 - 3.2 , can't upgrade , don't need serialize binary data, follow these instructions.

first declare field class:

from rest_framework import serializers  class jsonserializerfield(serializers.field):     """ serializer jsonfield -- required make field writable"""     def to_internal_value(self, data):         return data     def to_representation(self, value):         return value 

and add in field model like

class myserializer(serializers.modelserializer):     json_data = jsonserializerfield() 

and, if need serialize binary data, can copy official release code


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -