Django Rest Framework: Disable field update after object is created

后端 未结 11 1397
独厮守ぢ
独厮守ぢ 2020-11-30 20:15

I\'m trying to make my User model RESTful via Django Rest Framework API calls, so that I can create users as well as update their profiles.

However, as I go through

11条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 20:52

    Another method would be to add a validation method, but throw a validation error if the instance already exists and the value has changed:

    def validate_foo(self, value):                                     
        if self.instance and value != self.instance.foo:
            raise serializers.ValidationError("foo is immutable once set.")
        return value         
    

    In my case, I wanted a foreign key to never be updated:

    def validate_foo_id(self, value):                                     
        if self.instance and value.id != self.instance.foo_id:            
            raise serializers.ValidationError("foo_id is immutable once set.")
        return value         
    

    See also: Level-field validation in django rest framework 3.1 - access to the old value

提交回复
热议问题