路由问题, 已经解决! 然后就是视图函数的问题了:
不想重复写的解决途径就是, python 类的继承了!
写一个基类, 基类定义 增删改查。 然后其他的,全部去继承他!
from django.urls import path, re_path from django.http import HttpResponse, JsonResponse from django.shortcuts import render, redirect, reverse from app01 import models # 基类的,最初定义。简单一些! class StartHandler(object): def __init__(self, model_class): self.model_class = model_class def check_list_view(self, request): data_list = self.model_class.objects.all() return render(request, "changelist.html", locals()) def add_view(self, request): return HttpResponse("添加页面") def change_view(self, request): return HttpResponse("编辑页面") def delete_view(self, request): return HttpResponse("删除页面") class StartSite(object): def __init__(self): self._registry = [] self.app_name = "stark" self.namespace = "stark" def register(self, model_class, handler_class): ''' :param model_class: 是model中数据库相关类。 接受一个类而不是对象 :param handler_class: 处理请求的视图函数,所在的类 :return: ''' self._registry.append({'model_class': model_class, "handler": handler_class(model_class)}) ''' [ {'model_class':models.Depart, "handler":DepartHandler(models.Depart)}, {'model_class':models.UserInfo, "handler":UserInfoHandler(models.UserInfo)}, {'model_class':models.Host, "handler":HostHandler(models.Host)}, ] ''' def get_urls(self): partterns = [] for item in self._registry: model_class = item["model_class"] handler = item["handler"] app_label = model_class._meta.app_label # 获取当前model_class所在的app名字 model_name = model_class._meta.model_name # 获取当前model_class的类名,小写 partterns.append(re_path(r"%s/%s/list/$" % (app_label, model_name), handler.check_list_view)) partterns.append(re_path(r"%s/%s/add/$" % (app_label, model_name), handler.add_view)) partterns.append(re_path(r"%s/%s/change/(d+)/$" % (app_label, model_name), handler.change_view)) partterns.append(re_path(r"%s/%s/del/$(d+)/$" % (app_label, model_name), handler.delete_view)) return partterns @property def urls(self): '''模拟include的返回值''' return (self.get_urls(), self.app_name, self.namespace) site = StartSite()
app01start.py
from stark.servers.start_v1 import site,StartHandler from django.http import HttpResponse, JsonResponse from app01 import models class DepartHandler(StartHandler): '''定义增删改查''' pass
class UserInfoHandler(StartHandler): '''定义增删改查''' pass site.register(models.Depart, DepartHandler) site.register(models.UserInfo, UserInfoHandler)
app02start.py
from stark.servers.start_v1 import site, StartHandler from app02 import models class HostHandler(StartHandler): '''定义增删改查''' pass site.register(models.Host, HostHandler)
这样就可以了! 如果以后还想增加表的时候。 直接增加就行了!
定义一个 Handler 类。 继承StartHandler 。 然后 将model类, 和 刚刚为这张表定义的,类。 传给register() 就可以了