django基于restframework的CBV封装详解
作者:Maple_feng 时间:2021-09-25 20:25:25
目录
一.models数据库映射
二.serializers序列化
三.url路由
四.Views视图类
一.models数据库映射
from django.db import models
# Create your models here.
class Book(models.Model):
title=models.CharField(max_length=32)
price=models.IntegerField()
pub_date=models.DateField()
publish=models.ForeignKey(to="Publish")
authors=models.ManyToManyField(to="Author")
def __str__(self):
return self.title
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
二.serializers序列化
from rest_framework import serializers
from app01 import models
from rest_framework import exceptions
class BookSerialize(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = "__all__"
publish = serializers.SerializerMethodField()
authors = serializers.SerializerMethodField()
def get_publish(self, obj):
return {"publish_id": obj.publish.pk, "publish_name": obj.publish.name}
def get_authors(self, obj):
author_list = obj.authors.all()
lis = [{"name": author.name, "age": author.age} for author in author_list]
return lis
def validate_title(self, value):
if value.startswith("sb"):
raise exceptions.ValidationError('你使用了不合适的文字')
return value
三.url路由
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/$', views.Books.as_view()),
]
四.Views视图类
主要就是将CBV的几个get,post请求方法进行封装,以后创建其他的新的CBV,直接继承调用就可以了,可以减少代码冗余
from app01 import models
from rest_framework.response import Response
from rest_framework.views import APIView
from app01.serialize_module import BookSerialize
# 自定义一个response类,方便CBV使用
class MyResponse():
def __init__(self):
self.status = 100
self.msg = None
# 将类方法装饰成属性
@property
def get_dic(self):
return self.__dict__
# 封装CBV类
# 将get请求封装在List类中
class List():
def get_list(self, request,*args,**kwargs):
response = MyResponse()
try:
handler_list = self.model.objects.all()
handler_ser = self.serializer(instance=handler_list, many=True)
response.handler = handler_ser.data
response.msg = "获取成功"
except Exception as e:
response.msg="获取失败"
response.error=str(e)
return Response(response.get_dic)
# 将post请求封装在Create类中
class Create():
def save(self, request,*args,**kwargs):
response = MyResponse()
try:
handler_ser = self.serializer(data=request.data)
if handler_ser.is_valid():
handler_ser.save()
response.msg = "添加成功"
else:
response.status = 101
response.msg = "添加失败"
response.error = handler_ser.errors
except Exception as e:
response.msg = "添加失败"
response.error=str(e)
return Response(response.get_dic)
# book类继承List,Create,APIView
class Books(List,Create,APIView):
model=models.Book
serializer=BookSerialize
# 此时调用get方法时,只要使用List类中的get_list方法就行了
def get(self,request):
return self.get_list(request)
# 此时调用post方法时,只要使用Create类中的save方法就行了
def post(self,request):
return self.save(request)
来源:https://www.cnblogs.com/angelyan/p/10433100.html
标签:django,rest,framework,cbv,封装
0
投稿
猜你喜欢
利用PyQt5制作一个豆瓣电影信息查看器
2021-03-05 05:57:28
Python中and和or如何使用
2022-04-27 18:01:49
SQL CASE 表达式的具体使用
2024-01-28 09:57:29
pandas读取excel,txt,csv,pkl文件等命令的操作
2023-09-08 08:57:33
Python中切片的详细操作篇
2021-11-29 13:33:26
Python实现全局变量的两个解决方法
2021-03-23 22:43:44
PHP5在Apache下的两种模式的安装
2023-11-24 05:18:08
带有定位当前位置的百度地图前端web api实例代码
2024-05-08 10:11:56
Python虚拟环境的创建和使用详解
2022-09-14 18:05:26
记一次vue-webpack项目优化实践详解
2023-07-02 16:37:22
初步讲解Python中的元组概念
2022-06-03 23:05:55
VS2015安装之后加装Sql server2014详细步骤
2024-01-18 04:39:56
python最长回文串算法
2023-03-05 02:27:37
使用uni-app开发微信小程序的实现
2024-05-13 09:10:42
python实现TF-IDF算法解析
2021-06-02 03:27:51
从绘画语言的发展,看视觉设计风格
2008-08-03 17:11:00
Omi v1.0.2发布正式支持传递javascript表达式
2024-04-19 11:03:04
情人节快乐! python绘制漂亮玫瑰
2021-02-07 18:22:48
Django-migrate报错问题解决方案
2021-11-05 13:30:16
对Python3中dict.keys()转换成list类型的方法详解
2021-02-13 12:18:26