1.编辑 try_reqwest.html
增加一个 deleteData 方法:
var deleteData = function() {
var id = 1; // 书本的id
reqwest({
url: 'api/revise_book/' + id,
type: "json",
method: "delete", // delete 方法用于删除数据
success: function(resp) {}
})
};
2. 编辑 api.py
修改 revise_book 方法,增加删除数据的功能:
# put 方法用于修改数据,delete 方法用于删除数据
@api_view(['PUT', 'DELETE'])
# id参数来自url, 用于找到要改变的那条数据
def revise_book(request, id):
revise_book = Book.objects.get(id=id)
if request.method == 'PUT':
serializer = BookSerializer(revise_book, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# 删除数据
elif request.method == 'DELETE':
revise_book.delete()
return Response({'msg': 'A-OK'}, status=status.HTTP_201_CREATED)
3.测试
控制台输入:deleteData ,就能删除 id=1 的书了。