1 创建多对多表的方式有两种
1.1 方式一:自定义关系表
1 class Host(models.Model): 2 nid = models.AutoField(primary_key=True) 3 hostname = models.CharField(max_length=32,db_index=True) 4 ip = models.GenericIPAddressField(protocol="ipv4",db_index=True) 5 port = models.IntegerField() 6 b = models.ForeignKey(to="Business", to_field='id') 7 8 class Application(models.Model): 9 name = models.CharField(max_length=32) 10 11 12 class HostToApp(models.Model): 13 hobj = models.ForeignKey(to='Host',to_field='nid') 14 aobj = models.ForeignKey(to='Application',to_field='id')
那么我们可以通过对第三张表的操作HostToApp,增删改查各种多对多的关系:
models.HostToApp.objects.create(hobj_id=1,aobj_id=2)
1.2 方式二:自动创建第三张表
1 class Host(models.Model): 2 nid = models.AutoField(primary_key=True) 3 hostname = models.CharField(max_length=32,db_index=True) 4 ip = models.GenericIPAddressField(protocol="ipv4",db_index=True) 5 port = models.IntegerField() 6 b = models.ForeignKey(to="Business", to_field='id') 7 8 class Application(models.Model): 9 name = models.CharField(max_length=32) 10 r = models.ManyToManyField("Host")
这种方式无法直接操作第三张表,但是可以通过10行r这个对象,进行间接操作第三张表:
obj = models.Application.objects.get(id=1) obj.name # 第三张表操作 # 添加 obj.r.add(1) obj.r.add(2) obj.r.add(2,3,4) obj.r.add(*[1,2,3,4]) # 删除 obj.r.remove(1) obj.r.remove(2,4) obj.r.remove(*[1,2,3]) # 清除obj所对应的所有主机 obj.r.clear() # 设置,可以理解为删除原来的,设置成下面的 obj.r.set([3,5,7]) # 所有相关的主机对象“列表” QuerySet obj.r.all()
2 Ajax
为某个标签写个AJAX请求:
JS代码:
1 $('#app-edit5').click(function () { 2 $.ajax({ 3 url: "/cmdb/app_edit_ajax/", //提交给哪个url 4 type: "POST", //请求方式 5 data: $('#app-edit-form').serialize(), //请求数据可以以字典的形式,此处是获取这个form表单中的所有 6 traditional: true, // 提交数据中有数组 7 dataType: "JSON", // 写了这个不用反序列化data,data就直接是对象 8 success:function (data) { 9 if(data.status){ 10 location.reload(); //刷新页面 11 }else { 12 $('#app_edit_error').text(data.error); 13 } 14 } 15 }) 16 });
后端代码:
1 def app_edit_ajax(request): 2 if request.method == "POST": 3 ret = {'status': True, 'error': None, 'data': None} 4 aid = request.POST.get("nid") 5 app_name = request.POST.get("app-name") 6 h_list = request.POST.getlist("app-hosts") 7 try: 8 if app_name: 9 obj = models.Application.objects.filter(id=aid).first() 10 obj.name = app_name 11 obj.save() 12 obj.r.set(h_list) 13 else: 14 ret['status'] = False 15 ret['error'] = "应用名称不能为空" 16 except Exception as e: 17 print("错误信息:", e) 18 ret['status'] = False 19 ret['error'] = '请求错误' 20 21 return HttpResponse(json.dumps(ret))
3 Django总结
3.1 完整的Django的请求周期:
1 请求 -> 路由系统 -> 试图函数(获取模板+数据=》渲染) -> 字符串返回给用户
3.2 路由系统书写的几种方式
1 /index/ -> 函数或类.as_view() 2 /detail/(\d+) -> 函数(参数) 或 类.as_view()(参数) 3 /detail/(?P<nid>\d+) -> 函数(参数) 或 类.as_view()(参数) 4 5 /detail/ -> include("app01.urls") 6 /detail/ name='a1' -> include("app01.urls") 7 - 视图中:reverse 8 - 模板中:{% url "a1" %}
3.3 视图函数
FBV:
from django.views import View class Home(View): def dispatch(self, request, *args, **kwargs): print("before") result = super(Home, self).dispatch(request, *args, **kwargs) print("after") return result def get(self, request): print(request.method) return render(request, "home.html") def post(self, request): print(request.method, "post") return render(request, "home.html")
CBV:
def host(request): if request.method == "GET": h_dic = models.Host.objects.all() h_dic1 = models.Host.objects.filter(nid__gt=0).values('nid', 'hostname', 'b_id', 'b__caption') h_dic2 = models.Host.objects.filter(nid__gt=0).values_list('nid', 'hostname', 'b_id', 'b__caption') b_list = models.Business.objects.all() return render(request, "host.html", {'h_dic': h_dic, 'h_dic1': h_dic1, 'h_dic2': h_dic2, 'b_list': b_list}) elif request.method == "POST": h = request.POST.get("hostname", None) i = request.POST.get("ip", None) p = request.POST.get("port", None) b = request.POST.get("b_id", None) models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b) return redirect('/host/')
获取用户请求中的数据:
1 request.POST.get 2 request.GET.get 3 reqeust.FILES.get() #获取文件 4 5 # checkbox, 6 ........getlist() #获取列表 7 8 request.path_info # 获取路径 9 10 11 文件对象 = reqeust.FILES.get() 12 文件对象.name 13 文件对象.size 14 文件对象.chunks() 15 #依赖这个设置 <form enctype="multipart/form-data"></form>
给用户返回数据:
render(request, "模板的文件的路径", {'k1': [1,2,3,4],"k2": {'name': 'zingp','age': 73}}) redirect("URL") HttpResponse(字符串)
3.4 模板语言
# 视图函数中: render(request, "模板的文件的路径", {'obj': 1234, 'k1': [1,2,3,4],"k2": {'name': 'zingp','age': 73}}) #html <html> <body> <h1> {{ obj }} </h1> <h1> {{ k1.3 }} </h1> <h1> {{ k2.name }} </h1> {% for i in k1 %} <p> {{ i }} </p> {% endfor %} {% for row in k2.keys %} {{ row }} {% endfor %} {% for row in k2.values %} {{ row }} {% endfor %} {% for k,v in k2.items %} {{ k }} - {{v}} {% endfor %} </body> </html>