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

后端 未结 2 803
无人共我
无人共我 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: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.

提交回复
热议问题