Django Rest Framework: Disable field update after object is created

后端 未结 11 1413
独厮守ぢ
独厮守ぢ 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:45

    If you don't want to create another serializer, you may want to try customizing get_serializer_class() inside MyViewSet. This has been useful to me for simple projects.

    # Your clean serializer
    class MySerializer(serializers.ModelSerializer):
        class Meta:
            model = MyModel
            fields = '__all__'
    
    # Your hardworking viewset
    class MyViewSet(MyParentViewSet):
        serializer_class = MySerializer
        model = MyModel
    
        def get_serializer_class(self):
            serializer_class = self.serializer_class
            if self.request.method in ['PUT', 'PATCH']:
                # setting `exclude` while having `fields` raises an error
                # so set `read_only_fields` if request is PUT/PATCH
                setattr(serializer_class.Meta, 'read_only_fields', ('non_updatable_field',))
                # set serializer_class here instead if you have another serializer for finer control
            return serializer_class
    

    setattr(object, name, value)

    This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

提交回复
热议问题