简体   繁体   中英

How to provide additional data in “PUT” request for update in Django REST Framework?

Here is what I have so far:

[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)

[request]

http -a admin:password PUT http://localhost:8000/api/employees/list/2/

As a result I am able to update that employee with id=2, but the only thing that I am able to change is "employee_type" cause it has default value = 'manager', and if "employee_type" of that employee with id=2 is let's say "admin" after my request it will become "manager". The problem is that I can't figure out how to add some extra data to my request so I would be able to change "employee_type" to "director" for example, is something like below can be accomplished ?

[request_as_I_want]

http -a admin:password PUT http://localhost:8000/api/employees/list/2/employee_type='director'/company='some_value'/

Is that can be done, or I misunderstand something ?

I assume you are using httpie . To send a PUT request to django-rest-framework, a URL and json data is needed. Here's one way to do that (notice the space between URL and data):

http -a admin:password PUT http://localhost:8000/api/employees/list/2 employee_type='director' company='some_value'

See more at https://github.com/jakubroztocil/httpie#json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM