图书管理系统:
实现图书接口的增、删、改、查
方式一:普通的方式
views配置:
1 #Book的增、删、改、查接口 2 3 class BookSerializer(serializers.ModelSerializer): 4 class Meta: 5 model = models.Book 6 fields = '__all__' 7 depth = 1 8 9 #对get、post请求进行封装 10 #查看所有图书 11 class List(): 12 def list(self): 13 14 ret=self.query_set.objects.all() 15 ser=self.serila(instance=ret,many=True) 16 return Response(ser.data) 17 #创建图书 18 class Create(): 19 def create(self,request): 20 back_msg = {'status': 0, 'data': None, 'msg': '错误'} 21 ser = BookSerializer(data=request.data) 22 if ser.is_valid(): 23 ser.save() 24 back_msg['data'] = ser.data 25 back_msg['status'] = 1 26 back_msg['msg'] = '创建成功' 27 return Response(back_msg) 28 29 #创建书籍类,包含get、post方法(继承上面的List和Create类) 30 class Book(APIView,List,Create): 31 query_set=models.Book 32 serila=BookSerializer 33 def get(self,request): 34 return self.list() 35 def post(self,request): 36 return self.create(request) 37 38 #查看(查看单本书)、更新、删除 39 class BookDetail(APIView): 40 def get(self,request,pk): 41 ret= models.Book.objects.filter(pk=pk).first() 42 ser=BookSerializer(instance=ret,many=False) 43 return Response(ser.data) 44 def put(self,request,pk): 45 ret = models.Book.objects.filter(pk=pk).first() 46 ser=BookSerializer(instance=ret,data=request.data) 47 if ser.is_valid(): 48 ser.save() 49 return Response(ser.data) 50 def delete(self,request,pk): 51 models.Book.objects.filter(pk=pk).delete() 52 return HttpResponse('删除成功')
settings配置:
1 REST_FRAMEWORK = { 2 'DEFAULT_PARSER_CLASSES': ['rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser'] 3 }
备注:views里面局部的配置信息如下
1 #RESTfu自带的处理请求的模块方法 2 from rest_framework.parsers import JSONParser,FormParser #JSONParser,FormParser局部解析器,一般只需要写一个就行 3 class Book(APIView): 4 5 #解析器:对浏览器发送post请求过来的数据类型做解析 6 #当指向下面post请求,运行request.data的时候才会去执行解析器 7 parser_classes = [JSONParser,FormParser] 8 9 def get(self,request): #request是已经处理好的request 10 11 ret = models.Book.objects.all() 12 print(ret,type(ret)) #ret是QuerySet对象 <class 'django.db.models.query.QuerySet'> 13 14 # 实例化上面的BookSerializer拿到一个book_ser对象 15 # BookSerializer参数(ret:queryset对象,many=True代表序列化多条,many=False 代表序列化一条) 16 book_ser=BookSerializer(ret,many=True) 17 #book_ser.data不是json格式的字符串,而是个字典 18 #所以Response内部一定是对book_ser.data做了序列化 19 return Response(book_ser.data) 20 21 22 def post(self,request): 23 print('111') 24 print(request.data) 25 return HttpResponse('ok') 26 27 # 杂乱内容整理: 28 # print(request.POST) 29 #对请求过来的数据进项验证,检验每个字段是否符合录入要求,并保存 30 ser = BookSerializer(data=request.data) 31 32 #post请求过来数据符合每个字段要求,就允许写入数据库 33 if ser.is_valid(): 34 ser.save() 35 return Response(ser.save()) 36 37 #不符合要求就返回错误信息 38 else: 39 print(ser.errors) 40 41 return HttpResponse(json.dumps(ser.errors))
models配置:
1 from django.db import models 2 3 # Create your models here. 4 5 from django.db import models 6 7 class Book(models.Model): 8 title=models.CharField(max_length=32) 9 price=models.IntegerField() 10 pub_date=models.DateField() 11 publish=models.ForeignKey("Publish") 12 authors=models.ManyToManyField("Author") 13 14 def __str__(self): 15 return self.title 16 17 #我了验证可以覆盖重写字段的方法 18 def test(self): 19 return '555' 20 21 22 class Publish(models.Model): 23 name=models.CharField(max_length=32) 24 email=models.EmailField() 25 # def __str__(self): 26 # return self.name 27 28 class Author(models.Model): 29 name=models.CharField(max_length=32) 30 age=models.IntegerField() 31 def __str__(self): 32 return self.name
url路由配置:
urlpatterns = [ url(r'^admin/', admin.site.urls), #查看所有图书url(查看所有图书) url(r'^book/$', views.Book.as_view()), #指定具体查看某一本书信息(查看、更新、删除等) url(r'^book/(?P<pk>d+)', views.BookDetail.as_view()), ]
方式二:实现作者的增删改查
views配置:
1 #作者的增删改查 2 class AuthorSerializer(serializers.ModelSerializer): 3 class Meta: 4 model = models.Author 5 fields='__all__' 6 depth = 1 7 8 from rest_framework import mixins 9 from rest_framework.generics import GenericAPIView 10 #整合了方法一中的List、Create 11 class Authors(GenericAPIView,mixins.CreateModelMixin,mixins.ListModelMixin): 12 queryset = models.Author.objects.all() 13 serializer_class = AuthorSerializer 14 15 def get(self,request): 16 return self.list(request) 17 def post(self,request): 18 return self.create(request) 19 20 #设置查看单条数据详情 21 class AuthorsDetail(APIView): 22 def get(self,request,pk): 23 ret=models.Author.objects.filter(pk=pk).first() 24 ser=AuthorSerializer(instance=ret,many=False) 25 return Response(ser.data) 26 #更新单条作者信息 27 def put(self,request,pk): 28 ret=models.Author.objects.filter(pk=pk).first() 29 ser=AuthorSerializer(instance=ret,data=request.data) #注意这里是先拿到新的文件,去覆盖旧的文件 30 print('即将更新一个出版社信息') 31 if ser.is_valid(): 32 ser.save() 33 return Response(ser.data) 34 #删除单条作者信息 35 def delete(self,request,pk): 36 ret=models.Author.objects.filter(pk=pk).delete() 37 return HttpResponse('删除成功')
url路由配置:
1 urlpatterns = [ 2 url(r'^admin/', admin.site.urls), 3 #查看所有作者 4 url(r'^authors/$', views.Authors.as_view()), 5 #查看指定单个作者详情 6 url(r'^authors/(?P<pk>d+)', views.AuthorsDetail.as_view()), 7 8 ]
方式三: