金狮镖局 Design By www.egabc.com
一.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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
金狮镖局 Design By www.egabc.com
金狮镖局
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
金狮镖局 Design By www.egabc.com
暂无django基于restframework的CBV封装详解的评论...
更新日志
2024年11月18日
2024年11月18日
- 潘美辰《鹰与月》双语专辑[WAV+CUE][1G]
- 梁咏琪.2007-女色新曲+精选2CD【华纳】【WAV+CUE】
- 黎亚.2006-我不在巴黎【星外星】【FLAC分轨】
- 陈洁仪.1994-心痛【立得唱片】【WAV+CUE】
- 车载必备专用超级选曲《劲爆中文DJ》2CD[WAV+CUE]
- 群星《民歌流淌60年(黑胶CD)》2CD[WAV+分轨]
- 群星《美丽时光》紫银合金AQCD[WAV+CUE]
- 群星《12大巨星畅销精选集》[WAV分轨][1.1G]
- 华语排行冠军曲《百事音乐风云榜》[WAV+CUE][1G]
- 奔驰汽车音乐圣经《醇声典范[白金嗓子] 男极声》音乐传真[WAV+CUE][1G]
- 陈影《如影随形HQ》头版限量[低速原抓WAV+CUE]
- 黄乙玲1996-心痛酒来洗[台湾首版][WAV+CUE]
- 曾庆瑜1990-随风而逝[日本东芝1A1首版][WAV+CUE]
- 群星.2015-凭着爱ADMS2CD【华纳】【WAV+CUE】
- 陈冠希.2017-一只猴子3部曲【摩登天空】【WAV+CUE】