Django 不在URL中传递ID-UpdateAliView
我想使用我的Django 不在URL中传递ID-UpdateAliView,django,django-rest-framework,Django,Django Rest Framework,我想使用我的API进行更新。为此,我在URL中传递id,它是pk http://localhost:8000/api/manager/update/96 其中96是主键。现在,我不想在url中传递id,而是想在正文中传递id,并更新数据。我的url应该是这样的 http://localhost:8000/api/manager/update Views.py class ManagerUpdateAPIView(APIView): def post(self, request, p
API
进行更新。为此,我在URL
中传递id
,它是pk
http://localhost:8000/api/manager/update/96
其中96是主键
。现在,我不想在url中传递id
,而是想在正文中传递id
,并更新数据。我的url应该是这样的
http://localhost:8000/api/manager/update
Views.py
class ManagerUpdateAPIView(APIView):
def post(self, request, pk, *args, **kwrgs):
user = get_object_or_404(User, id=pk)
userprofile = get_object_or_404(UserProfile, user=pk)
serializer1 = EmployeeRegisterSerializer(user, data=request.data)
serializer2 = EmployeeProfileSerializer(userprofile, data=request.data)
user_role = ACLRoles.objects.get(id=4)
if serializer1.is_valid() and serializer2.is_valid():
serializer1.save()
serializer2.save()
return Response(status=status.HTTP_200_OK)
print(serializer1.errors)
print(serializer2.errors)
return Response(status=status.HTTP_404_NOT_FOUND)
序列化程序.py
class EmployeeProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = [
'user_employee_id',
'user_phone',
'user_payroll_id',
'user_hire_date',
'user_pay_rate',
'user_salaried',
'user_excempt',
'user_groups',
'user_state',
'user_city',
'user_zipcode',
'user_status',
]
class EmployeeRegisterSerializer(serializers.ModelSerializer):
# userprofile = EmployeeProfileSerializer(read_only=True)
class Meta:
model = User
fields = ['first_name','last_name', 'email',]
如何更新数据而不在url中传递id
。请尝试此代码
class ManagerUpdateAPIView(APIView):
def post(self, request, *args, **kwrgs): #change is here
pk = request.data['pk'] #change is here
user = get_object_or_404(User, id=pk)
userprofile = get_object_or_404(UserProfile, user=pk)
serializer1 = EmployeeRegisterSerializer(user, data=request.data)
serializer2 = EmployeeProfileSerializer(userprofile, data=request.data)
user_role = ACLRoles.objects.get(id=4)
if serializer1.is_valid() and serializer2.is_valid():
serializer1.save()
serializer2.save()
return Response(status=status.HTTP_200_OK)
print(serializer1.errors)
print(serializer2.errors)
return Response(status=status.HTTP_404_NOT_FOUND)
如果我没有发送数据,其中一个字段会出现错误-
serializer2{'salaried':[ErrorDetail(string='This field is required',code='required')],'excempt':[ErrorDetail(string='This field is required',code='required')]
您也必须在消息payload中传递这些数据。我不知道是哪个负载。我正在传递serializer2=EmployeeProfileSerializer(userprofile,data=request.data)
Payload是您发送给drf的数据,我如何传递它,因为serializer1=EmployeeRegisterSerializer(user,data=request.data)
即使我不发送任何数据,它也在完美地更新我的数据。Justserializer2
不起作用
{
"pk":96,
"other_data":"other data of your usual payload"
}