本文介绍了Django Rest 框架和 JSONField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个带有 JSONField 的 Django 模型,使用 ?

Given a Django model with a JSONField, what is the correct way of serializing and deserializing it using Django Rest Framework?

我已经尝试创建自定义 serializers.WritableField 并覆盖 to_nativefrom_native:

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)

但是当我尝试使用 partial=True 更新模型时,JSONField 对象中的所有浮点数都变成了字符串.

But when I try to updating the model using partial=True, all the floats in the JSONField objects become strings.

推荐答案

如果您使用的是 Django Rest Framework >= 3.3,那么 JSONField 序列化程序是 现在包括.这是现在正确的方法.

If you're using Django Rest Framework >= 3.3, then the JSONField serializer is now included. This is now the correct way.

如果您使用的是 Django Rest Framework <3.0,然后看gzerone的回答.

If you're using Django Rest Framework < 3.0, then see gzerone's answer.

如果您使用的是 DRF 3.0 - 3.2 并且您无法升级并且您不需要序列化二进制数据,请按照这些说明进行操作.

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.

首先声明一个字段类:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!