drf 基于View的5个接口

2023-05-15  本文已影响0人  晨颜
class BookViews(View):
    def get(self,request):
        print('getall')
        book_list=models.Book.objects.all()
        print(book_list)
        books=[]
        print(books)
        for each in book_list:
            print(each.name,each.price)
            books.append({'name': each.name,'price':each.price})
            print(books)
        # return JsonResponse(books)
        ##########################
        return JsonResponse({'code': 100, 'msg': '查询全部信息成功','result':books})
    def post(self,request):
        print('add,post')
        print(request.body)
        add_book=json.loads(request.body)
        print(request.body)
        print(request.POST)
        # models.Book.objects.create()
        name=add_book.get('name')
        price=add_book.get('price')
        print(name,price)
        models.Book.objects.create(name=name,price=price)
        return JsonResponse({'code': 100, 'msg': 'add成功'})
class BookDetailViews(View):
    def get(self,request,pk):
        print('getdetail')
        book_detail=models.Book.objects.filter(pk=pk).first()
        book={}
        book['name']=book_detail.name
        book['price']=book_detail.price

        return JsonResponse({'code': 100, 'msg': 'getdetail成功','result':book})

    def put(self, request, pk):
        print(request.body)
        print(json.loads(request.body))
        updata_book=json.loads(request.body)
        name=updata_book.get('name')
        price=updata_book.get('price')
        models.Book.objects.filter(pk=pk).update(name=name,price=price)
        return JsonResponse({'code': 100, 'msg': '成功'})
    def delete(self, request, pk):
        models.Book.objects.filter(pk=pk).delete()
        return JsonResponse({'code': 100, 'msg': '成功'})
上一篇下一篇

猜你喜欢

热点阅读