我想使用我的API
进行更新。为此,我在id
的{{1}}中传递了URL
。
pk
其中96是http://localhost:8000/api/manager/update/96
。现在,我不想在URL中传递primary key
,而是在正文中传递id
并更新数据。我的网址应该是这样
id
Views.py
http://localhost:8000/api/manager/update
Serializers.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)
如何在不通过url传递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',]
的情况下更新数据。
答案 0 :(得分:1)
尝试此代码
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)
,并在POST负载中提供 pk
为
{
"pk":96,
"other_data":"other data of your usual payload"
}