Django-如何执行PATCH请求-ModelSerializer,RetrieveUpdateDestroyAPIView

时间:2018-07-21 08:03:20

标签: django authentication django-rest-framework http-put http-patch

我有一个ProfileSerializer的{​​{1}}:

ModelSerializer

而且,我有一个名为class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data, username=validated_data.get('username')) profile = Profile.objects.create(user=user, **validated_data) return profile def update(self, instance, validated_data): instance.dob = validated_data.get('dob', instance.dob) instance.karma = validated_data.get('karma', instance.karma) instance.username = validated_data.get('username', instance.username) user_data = validated_data.pop('user') instance.user.first_name = user_data.get('first_name', instance.user.first_name) instance.user.last_name = user_data.get('last_name', instance.user.last_name) instance.user.email = user_data.get('email', instance.user.email) instance.user.username = instance.username new_password = user_data.get('password') if new_password: instance.user.set_password(new_password) instance.user.save() instance.save() return instance class Meta: model = Profile fields = '__all__' 的视图,它是一个DetailProfile

RetrieveUpdateDestroyAPIView

问题是每当我执行 PUT 请求时,我都必须发送包括密码在内的所有字段。现在,我从 GET 请求中获得的密码已散列。因此,如果我在 PUT 请求中发送了相同的哈希密码,则该密码将替换为该字符串(看起来像class DetailProfile(RetrieveUpdateDestroyAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'username' lookup_url_kwarg = 'username' )。

因此,我想发出 PATCH 请求,而不发送密码。

1 个答案:

答案 0 :(得分:2)

您可以覆盖put方法并添加partial参数,这将启用部分更新逻辑:

class DetailProfile(RetrieveUpdateDestroyAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'username'
    lookup_url_kwarg = 'username'

    def put(self, request, *args, **kwargs):
        kwargs['partial'] = True 
        return self.update(request, *args, **kwargs)

BTW补丁请求也可用于RetrieveUpdateDestroyAPIView。因此,如果您同时需要PUT和PATCH,则可以使用它们而不必重写put()方法。