Model 图书管理案例
class BookModel(models.Model):
title = models.CharField(max_length=32,verbose_name='书名')
pub_date = models.DateField(verbose_name='发布日期')
desc = models.CharField(max_length=320,verbose_name='简介')
read = models.IntegerField(default=0,verbose_name='阅读量')
is_delete = models.BooleanField(default=False,verbose_name='逻辑删除')
View 实现添加动能
class BookView(View):
def post(self,request):
data = json.loads(request.body.decode())
title = data.get('title')
pub_date = data.get('pub_date')
desc = data.get('desc')
book = BookModel.objects.create(title=title,pub_date=pub_date,desc=desc)
book_dict = {
'id':book.id,
'title':book.title,
'pub_date':book.pub_date,
'read':book.read,
'desc':book.desc,
}
return JsonResponse(book_dict,status=201)
View 实现查看动能
class BookView(View):
def get(self,request,pk=None):
# 查看单条数据
if pk:
try:
book = BookModel.objects.get(pk=pk)
book_dict = {
'id': book.id,
'title': book.title,
'pub_date': book.pub_date,
'desc': book.desc,
'read': book.read,
}
return JsonResponse(book_dict)
except Exception as e:
return JsonResponse({'code':400,'msg':'pk不存在'})
# 查看多条数据
else:
books = BookModel.objects.all()
book_list = []
for book in books:
book_dict = {
'id':book.id,
'title':book.title,
'pub_date':book.pub_date,
'desc':book.desc,
'read':book.read,
}
book_list.append(book_dict)
return JsonResponse(book_list,safe=False)
View 实现修改动能
class BookView(View):
def put(self,request,pk=None):
try:
book = BookModel.objects.get(pk=pk)
data = json.loads(request.body.decode())
title = data.get('title')
pub_date = data.get('pub_date')
book.title=title
book.pub_date=pub_date
book.save()
book_dict = {
'id': book.id,
'title': book.title,
'pub_date': book.pub_date,
'desc': book.desc,
'read': book.read,
}
return JsonResponse(book_dict)
except Exception as e:
return JsonResponse({'code':400,'msg':'pk不存在'})
View 实现删除动能
class BookView(View):
def delete(self,request,pk=None):
try:
book = BookModel.objects.get(pk=pk)
book.is_delete=True
book.save_base()
return HttpResponse('ok')
except Exception as e:
return JsonResponse({'code':400,'msg':'pk不存在'})