Django REST Framework - Serializing optional fields

后端 未结 6 1470
天涯浪人
天涯浪人 2020-12-08 19:30

I have an object that has optional fields. I have defined my serializer this way:

class ProductSerializer(serializers.Serializer):
    code = serializers.Fie         


        
6条回答
  •  甜味超标
    2020-12-08 20:19

    The serializers are deliberately designed to use a fixed set of fields so you wouldn't easily be able to optionally drop out one of the keys.

    You could use a SerializerMethodField to either return the field value or None if the field doesn't exist, or you could not use serializers at all and simply write a view that returns the response directly.

    Update for REST framework 3.0 serializer.fields can be modified on an instantiated serializer. When dynamic serializer classes are required I'd probably suggest altering the fields in a custom Serializer.__init__() method.

提交回复
热议问题