django基于restframework的CBV封装详解
一.models数据库映射
fromdjango.dbimportmodels #Createyourmodelshere. classBook(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): returnself.title classPublish(models.Model): name=models.CharField(max_length=32) email=models.EmailField() def__str__(self): returnself.name classAuthor(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() def__str__(self): returnself.name
二.serializers序列化
fromrest_frameworkimportserializers fromapp01importmodels fromrest_frameworkimportexceptions classBookSerialize(serializers.ModelSerializer): classMeta: model=models.Book fields="__all__" publish=serializers.SerializerMethodField() authors=serializers.SerializerMethodField() defget_publish(self,obj): return{"publish_id":obj.publish.pk,"publish_name":obj.publish.name} defget_authors(self,obj): author_list=obj.authors.all() lis=[{"name":author.name,"age":author.age}forauthorinauthor_list] returnlis defvalidate_title(self,value): ifvalue.startswith("sb"): raiseexceptions.ValidationError('你使用了不合适的文字') returnvalue
三.url路由
fromdjango.conf.urlsimporturl fromdjango.contribimportadmin fromapp01importviews urlpatterns=[ url(r'^admin/',admin.site.urls), url(r'^books/$',views.Books.as_view()), ]
四.Views视图类
主要就是将CBV的几个get,post请求方法进行封装,以后创建其他的新的CBV,直接继承调用就可以了,可以减少代码冗余
fromapp01importmodels fromrest_framework.responseimportResponse fromrest_framework.viewsimportAPIView fromapp01.serialize_moduleimportBookSerialize #自定义一个response类,方便CBV使用 classMyResponse(): def__init__(self): self.status=100 self.msg=None #将类方法装饰成属性 @property defget_dic(self): returnself.__dict__ #封装CBV类 #将get请求封装在List类中 classList(): defget_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="获取成功" exceptExceptionase: response.msg="获取失败" response.error=str(e) returnResponse(response.get_dic) #将post请求封装在Create类中 classCreate(): defsave(self,request,*args,**kwargs): response=MyResponse() try: handler_ser=self.serializer(data=request.data) ifhandler_ser.is_valid(): handler_ser.save() response.msg="添加成功" else: response.status=101 response.msg="添加失败" response.error=handler_ser.errors exceptExceptionase: response.msg="添加失败" response.error=str(e) returnResponse(response.get_dic) #book类继承List,Create,APIView classBooks(List,Create,APIView): model=models.Book serializer=BookSerialize #此时调用get方法时,只要使用List类中的get_list方法就行了 defget(self,request): returnself.get_list(request) #此时调用post方法时,只要使用Create类中的save方法就行了 defpost(self,request): returnself.save(request)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。