def book(request, book_id): if request.method == 'GET': books = Book.objects.all() books_json = list(map(lambda book: book.to_dict(), books)) data = { 'status': 200, 'msg': 'ok', 'data': books_json, } return JsonResponse(data=data) elif request.method == 'POST': b_name = request.POST.get('b_name') b_price = request.POST.get('b_price') # b_name = '西游' # b_price = 32 # print(b_name, b_price) book = Book() book.b_name = b_name book.b_price = b_price book.save() data = { 'status': 201, 'msg': 'add success', 'data': book.to_dict(), } return JsonResponse(data=data) elif request.method == 'PUT': b_price = request.POST.get('b_price') # b_price = 999.99 print(b_price) book = Book.objects.get(pk=book_id) book.b_price = b_price book.save() data = { 'status': 201, 'msg': 'PUT', 'data': book.to_dict(), } return JsonResponse(data=data) elif request.method == 'DELETE': book = Book.objects.get(pk=book_id) book.delete() data = { 'status': 204, 'msg': 'delete', } return JsonResponse(data=data)
def books(request): if request.method == "GET": book_list = Book.objects.all() print(type(book_list)) book_list_json = [] for book in book_list: book_list_json.append(book.to_dict()) data = { # 通常给前端看这个状态码 'status': 200, 'msg': 'ok', 'data': book_list_json, } # 对传输时的状态码进行改变 return JsonResponse(data=data, status=201) elif request.method == "POST": b_name = request.POST.get('b_name') b_price = request.POST.get('b_price') book = Book() book.b_name = b_name book.b_price = b_price book.save() print("ok") data = {'status': 201, 'msg': 'add success', 'data': book.to_dict()} return JsonResponse(data=data)
def books(request): if request.method == 'GET': book_list = Book.objects.all() book_list_json = [] for book in book_list: book_list_json.append(book.to_dict()) data = {"status": 200, "msg": "ok", "data": book_list_json} return JsonResponse(data=data) elif request.method == 'POST': b_name = request.POST.get('b_name') b_price = request.POST.get('b_price') book = Book() book.b_price = b_price book.b_name = b_name book.save() data = { 'status': 201, 'msg': 'add success', 'data': book.to_dict(), } return JsonResponse(data=data, status=201)
def books(request): if request.method == 'GET': book = Book.objects.all() book_list = list() for i in book: book_list.append(i.to_dict()) data = { 'status': 200, 'msg': 'add_success', 'data': book_list, } return JsonResponse(data) elif request.method == 'POST': b_name = request.POST.get('b_name') b_price = request.POST.get('b_price') book = Book() book.b_name = b_name book.b_price = b_price book.save() data = { 'status': 201, 'msg': 'add_success', 'data': book.to_dict(), } return JsonResponse(data=data, status=data['status'])