django-rest-framework: How Do I Serialize a Field That Already Contains JSON?

后端 未结 3 2188
孤街浪徒
孤街浪徒 2021-01-05 23:20

I am pretty new to the django-rest-framework, so could use some help.

I have an object with a TextField that is a string containing JSON.

I\'m using django-r

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-06 00:06

    I solved this another way:

    1: use a JSON-Field for the JSON content (django-jsonfield or django-json-field should be fine). These then will to loads/dumps as needed

    2: in my serializer, use the transform-method to prevent the data added as string to the response

    class MyModelSerializer(serializers.ModelSerializer):
        def transform_myjsonfield(self, obj, value):
            return obj.myjsonfield
    
        class Meta:
            model = MyModel
    

    If you need write-access, you only have to add a method validate_myjsonfield which converts back.

    (of course, this could be also done with a custom DRF serializer field.

提交回复
热议问题