Django Rest Framework and JSONField

后端 未结 11 1984
眼角桃花
眼角桃花 2020-11-29 03:28

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

11条回答
  •  失恋的感觉
    2020-11-29 04:21

    If you're using mysql (haven't tried with other databases), using both DRF's new JSONField and Mark Chackerian's suggested JSONSerializerField will save the json as a {u'foo': u'bar'} string. If you rather save it as {"foo": "bar"}, this works for me:

    import json
    
    class JSONField(serializers.Field):
        def to_representation(self, obj):
            return json.loads(obj)
    
        def to_internal_value(self, data):
            return json.dumps(data)
    

提交回复
热议问题