django接口开发-代码优化views_get,urls

#利用cbv的继承特性,进行views中代码优化

#把views中的代码拆出来,新建custom_view.py,把cbv-class从views中挪进去

#自定义view,custom_view.py中新建一个BaseView 用于定义条件变量
import datetime
from itertools import chain

from django.core.paginator import Paginator
from django.db.models import Model
from django.http import JsonResponse
from django.views import View
from example import models

def model_to_dict(instance, fields=None, exclude=None):
    opts = instance._meta
    data = {}
    for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
        if fields and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        value = f.value_from_object(instance)
        if isinstance(value, datetime.datetime):
            value = value.strftime('%Y-%m-%d %H:%M:%S')
        if isinstance(value, datetime.date):
            value = value.strftime('%Y-%m-%d')
        data[f.name] = value
    return data

#BaseView中定义条件变量
class BaseView(View):
    model_class = None   #1-传递类变量
    fields = []          #2-返回指定字段
    exclude_fields = []  #3-指定返回时过滤掉哪些字段
    filter_fields = []  #4-按照什么字段进行过滤
    search_fields = []  #5-按照什么字段进行模糊匹配,前端传key=search的字段

    #1-验证model_clsss不传的时候
    @property
    def model(self):
        #issubclass:参数1是不是参数2的子类,校验model_class
        if self.model_class and issubclass(self.model_class,Model):
            return self.model_class
        raise Exception("未定义model_class")

    def get_filter_dict(self):
        filter_dict = {}
        for filed in self.filter_fields:
            #通过request取到name值
            value = self.request.GET.get(filed)
            if value:
                filter_dict[filed] = value
        return filter_dict

    def get_search_dict(self):   #只能模糊查询一个字段
        search_dict = {}
        value = self.request.GET.get('search')
        if value:
            search_dict = {"%s__contains" %self.search_fields[0]:value}
        return search_dict
def get_search_dict2(self): #实现多个字段模糊匹配,字段间是or的关系
q = Q() #Q,什么条件都没有
value = self.request.GET.get('search')
if value:
for filed in self.search_fields:
d ={"%s__contains" %filed:value}
q = Q(**d) |q
return q
#把复用接口方法变成共用方法, class GetView(BaseView): def get(self,requests): # get请求时 获取传递过来的第几页数据 page = requests.GET.get('page') filter_dict = self.get_filter_dict() search_dict = self.get_search_dict()
search_q = self.get_search_dict2()
#增加过滤条件,获取查询结果 qs = self.model_class.bojects.filter(is_delete=0).filter(filter_dict).filter(**search_dict).filter(search_q) page_obj = Paginator(qs, 5) # 获取第几页的数据 page_data = page_obj.get_page(page) # 用于存储返回的dict类型数据 data_list = [] for data in page_data: # 通过 model_to_dict转换成dict,exclude过滤哪些字段 tmp_data = model_to_dict(data, fields=self.fields,exclude=self.exclude_fields) data_list.append(tmp_data) return JsonResponse({"code": 0, "data": data_list})

#老的views中只需传入条件:

from .custom_view import GetView

#简化代码 ,继承
class SParameter(GetView):
    model_class = models.Parameter   #1-重写类变量,指定操作的数据
    fields = ['name']                #2-指定返回name字段
    exclude_fields = ['name']        #3-返回字段过滤掉name字段
    filter_fields = ['name']         #4-按照name进行过滤
    search_fields = ['name']         #5-按照name进行模糊匹配

#urls优化,在子项目下创建一个urls.py

 #url优化(CBV),在路由访问时,请求的是指向的类中的方法, get请求就访问def get、post请求进来就访问def post

#子urls引用custom_views逻辑
from
django.urls import path from .views import f_parameter,SParameter urlpatterns = [ # fbv path('f_parameter', f_parameter), # cbv # path('c_parameter', Parameter.as_view()), # 优化代码后cbv路由 path('s_parameter', SParameter.as_view()), ]

#老urls中再引用子项目下的urls

from django.urls import path,include
from example import urls

urlpatterns = [

    #通过include 将其他app的路由导入进来
    #api是base目录,每个example当中的路由都会加上api/
    path('api/',include(urls)),
]

 

posted @ 2020-09-11 15:04  whcp  阅读(220)  评论(0编辑  收藏  举报