1、对于FBV
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from api.models import Book
@csrf_exempt
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,
'message': 'ok',
'data': book_list_json
}
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,
"message": 'add success',
'data': book.to_dict()
}
return JsonResponse(data, status=201)
@csrf_exempt
def book(request, book_id):
if request.method == 'GET':
book = Book.objects.get(pk=book_id)
data = {
'status': 200,
'message': 'ok',
'data': book.to_dict()
}
return JsonResponse(data=data)
elif request.method == 'DELETE':
book_obj = Book.objects.get(pk=book_id)
book_obj.delete()
data = {
'message': 'delete success',
'status': 204,
}
return JsonResponse(data=data, status=204)
2、对于CBV
待补充~
网友评论