CBV与FBV最大区别是先创建类然后创建视图函数,CBV符合大的业务场景中进行使用。
urls路由:
urlpatterns = [
# 执行添加、查询所有数据,批量删除
path('books/', views.BooksCBV.as_view()),
# 根据id查询数据,执行修改、删除、查询一条或多条数据
path('book/<int:id>/', views.BooksCBVone.as_view()),
# 根据id查询数据,执行批量删除
path('alldel_book/', views.AllDel_CBV.as_view()),
]
models表:
class Book(models.Model):
b_name = models.CharField(max_length=32)
b_price = models.FloatField(default=1)
class Meta:
db_table = 'CBV_Book'
def to_dict(self):
return {'id': self.id, 'b_name': self.b_name, 'b_price': self.b_price}
views视图:
class BooksCBV(View):
# 查询所有数据
def get(self, request):
book_list = Book.objects.all()
book_list_json = []
for book in book_list:
book_list_json.append(book.to_dict())
data = {
'status': 200,
'msg': 'view all message success',
'data': book_list_json
}
return JsonResponse(data=data)
# 添加数据,通过post获取参数
def post(self, request):
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 = {
# 201代表创建或更新成功
'status': 201,
'msg': 'add success',
'data': book.to_dict()
}
return JsonResponse(data=data)
class BooksCBVone(View):
# 查看一条数据
def get(self, request, id):
book_obj = Book.objects.get(pk=id)
data = {
'status': 200,
'msg': 'view a message success',
'data': book_obj.to_dict()
}
return JsonResponse(data=data)
# 更新一条数据
def post(self, request, id):
book = Book.objects.get(pk=id)
b_name = request.POST.get("b_name")
b_price = request.POST.get("b_price")
# 获取参数后进行保存
book.b_name = b_name
book.b_price = b_price
book.save()
data = {
# 201代表创建或更新成功
'status': 201,
'msg': 'update success',
'data': book.to_dict()
}
return JsonResponse(data=data)
# 删除一条数据
def delete(self, request, id):
# 通过id传参和delete函数删除一条记录
book_obj = Book.objects.get(pk=id).delete()
data = {
'status': 204,
'msg': 'delete success',
}
return JsonResponse(data=data)
class AllDel_CBV(View):
# 批量删除数据
def post(self, request):
id = request.POST.getlist('id')
idstring = ','.join(id)
Book.objects.extra(where=['id IN (' + idstring + ')']).delete()
data = {
'status': 204,
'msg': 'delete success',
}
return JsonResponse(data=data)