Django Rest Framework - Read nested data, write integer

前端 未结 4 854
轻奢々
轻奢々 2021-01-01 14:39

So far I\'m extremely happy with Django Rest Framework, which is why I alsmost can\'t believe there\'s such a large omission in the codebase. Hopefully someone knows of a wa

4条回答
  •  鱼传尺愫
    2021-01-01 15:16

    You can create a Customized Serializer Field (http://www.django-rest-framework.org/api-guide/fields)

    The example took from the link:

    class ColourField(serializers.WritableField):
        """
        Color objects are serialized into "rgb(#, #, #)" notation.
        """
        def to_native(self, obj):
            return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
    
        def from_native(self, data):
            data = data.strip('rgb(').rstrip(')')
            red, green, blue = [int(col) for col in data.split(',')]
            return Color(red, green, blue)
    

    Then use this field in your serializer class.

提交回复
热议问题