To update an object, you have to edit a view function. This is because updating an object usually involves sending a put or patch request to an endpoint(which is handled by a view function)
So to update a product, you should modify the “product_detail” function, to accept put/patch requests. Now after you have specified the http methods on your view function, you need to check the method and perform a function on each one. If the method is a GET, get and serialize the object and return it. If the method is a PUT, we need to deserialize the object, validate it and save it in the database. When youre deserializing the object to be updated, you need to pass in an instance of that object to the serializer class, and then the data you wanna update it with.
@api_view(['GET', 'PUT'])def product_detail(request, id): product = get_object_or_404(Product, pk=id) if request.method == 'GET': serializer = ProductSerializer(product) return Response(serializer.data) elif request.method == 'PUT': '''we want to replace product with the request.data''' serializer = ProductSerializer(product, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)