Django REST Framework - Serializing optional fields

后端 未结 6 1463
天涯浪人
天涯浪人 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:20

    From the "it's a terrible hack relying on specific implementation details of both DRF and Django, but it works (at least for now)" files, here's the approach I used to include some additional debugging data in the response from a "create" method implementation on a serializer:

    def create(self, validated_data)
        # Actual model instance creation happens here...
        self.fields["debug_info"] = serializers.DictField(read_only=True)
        my_model.debug_info = extra_data
        return my_model
    

    This is a temporary approach that lets me use the browsable API to display some of the raw response data received from a particular remote service during the creation process. In the future, I'm inclined to keep this capability, but hide it behind a "report debugging info" flag in the creation request rather than returning the lower level info by default.

提交回复
热议问题