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