Unable to get a non-model field in the validated_data of a Django Rest Framework serializer

后端 未结 2 781
无人共我
无人共我 2021-01-11 15:18

I have an ItemCollection and Items in my Django models and I want to be able to remove Items from the collection through the UI. In a REST PUT request I add an extra boolean

相关标签:
2条回答
  • 2021-01-11 15:37

    If you're doing a PUT request, your view is probably calling self.perform_update(serializer). Change it for

    serializer.save(<my_non_model_field>=request.data.get('<my_non_model_field>', <default_value>)
    

    All kwargs are passed down to validated_data to your serializer. Make sure to properly transform incoming value (to boolean, to int, etc.)

    0 讨论(0)
  • 2021-01-11 15:38

    You can add non-model fields back by overwriting the to_internal_value fn:

    def to_internal_value(self, data):
        internal_value = super(MySerializer, self).to_internal_value(data)
        my_non_model_field_raw_value = data.get("my_non_model_field")
        my_non_model_field_value = ConvertRawValueInSomeCleverWay(my_non_model_field_raw_value)
        internal_value.update({
            "my_non_model_field": my_non_model_field_value
        })
        return internal_value
    

    Then you can process it however you want in create or update.

    0 讨论(0)
提交回复
热议问题