问题描述
给出使用的Django模型,使用?我已经尝试了一个自定义的 serializers.WritableField
并覆盖 to_native
和 from_native
:
$ j $ _ code从json_field.fields导入JSONEncoder,JSONDecoder
从rest_framework导入序列化程序
类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)
但是当我尝试使用 partial = True
,JSONField对象中的所有浮点变为字符串。
如果使用Django Rest Framework> = 3.3,那么JSONField序列化程序是
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'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:
from rest_framework import serializers
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return data
def to_representation(self, value):
return value
And then add in the field into the model like
class MySerializer(serializers.ModelSerializer):
json_data = JSONSerializerField()
And, if you do need to serialize binary data, you can always the copy official release code
这篇关于Django Rest框架和JSONField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!