我在Django Rest Framework中使用PATCH方法用户模型时遇到问题。希望你的家伙帮忙,节省我的时间。
Urls.py
urlpatterns = [
url(r'^account/edit/$', UserDetailAPIView.as_view({'patch': 'edit'}))
]
Views.py:
class UserDetailAPIView(ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
@detail_route(methods=['PATCH'])
def edit(self, request):
user_obj = User.objects.get(id=request.user.id)
serializer = UserRegisterSerializer(user_obj, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(status=status.HTTP_400_BAD_REQUEST)
串行器:
class UserRegisterSerializer(ModelSerializer):
class Meta:
model = User
fields = [
'email',
'first_name',
'last_name'
]
错误:
It's not partial update. It update all fields with let it blank.
答案 0 :(得分:1)
使用patch
时,您只需将更新后的字段传递给您的API。例如,要更新电子邮件,您需要发送此邮件:{'emai':'test@test.com'}
。换句话说,你不需要提供所有序列化程序。