这是我到目前为止所做的:
[serializers.py]
class EmployeeSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
user = UserSerializer(required=False)
company = serializers.CharField(read_only=True)
employee_type = serializers.ChoiceField(choices=EMPLOYEE_TYPES, default='manager')
is_blocked = serializers.BooleanField(required=False)
def update(self, instance, validated_data):
instance.user = validated_data.get('user', instance.user)
instance.company = validated_data.get('company', instance.company)
instance.employee_type = validated_data.get('employee_type', instance.employee_type)
instance.is_blocked = validated_data.get('is_blocked', instance.is_blocked)
instance.save()
return instance
[views.py]
class EmployeeDetail(APIView):
def get_employee(self, pk):
try:
return Employee.objects.get(pk=pk)
except Employee.DoesNotExist:
raise Http404
def put(self, request, pk, format=None):
employee = self.get_employee(pk)
serializer = EmployeeSerializer(employee, data=request.data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
else:
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
[请求]
http -a admin:password PUT http://localhost:8000/api/employees/list/2/
因此,我能够更新id = 2的员工,但我唯一可以改变的是" employee_type"因为它有默认值='经理',如果" employee_type"那个id = 2的员工应该说" admin"在我提出要求后,它将成为"经理"。问题是我无法弄清楚如何在我的请求中添加一些额外的数据,因此我可以更改" employee_type"到"导演"例如,下面的事情可以完成吗?
[request_as_I_want]
http -a admin:password PUT http://localhost:8000/api/employees/list/2/employee_type='director'/company='some_value'/
这可以做到,还是我误解了什么?
答案 0 :(得分:2)
我假设你正在使用httpie
。要向django-rest-framework发送PUT请求,需要URL和json数据。这是一种方法(注意URL和数据之间的空间):
http -a admin:password PUT http://localhost:8000/api/employees/list/2 employee_type='director' company='some_value'
了解详情