Django Rest Framework: Disable field update after object is created

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

    Another option (DRF3 only)

    class MySerializer(serializers.ModelSerializer):
        ...
        def get_extra_kwargs(self):
            extra_kwargs = super(MySerializer, self).get_extra_kwargs()
            action = self.context['view'].action
    
            if action in ['create']:
                kwargs = extra_kwargs.get('ro_oncreate_field', {})
                kwargs['read_only'] = True
                extra_kwargs['ro_oncreate_field'] = kwargs
    
            elif action in ['update', 'partial_update']:
                kwargs = extra_kwargs.get('ro_onupdate_field', {})
                kwargs['read_only'] = True
                extra_kwargs['ro_onupdate_field'] = kwargs
    
            return extra_kwargs
    

提交回复
热议问题