django进阶(四)之创建多对多关系表
多个表相互关联
方式一、创建多对多自定义关系表(创建第三方表关联两个表或多个表)
from django.db import models ##服务表,即所属哪个服务 class Service(models.Model): caption = models.CharField(max_length=32) code = models.CharField(max_length=8) ##新加字段,可以加上null=true 或者default = ''
#主机表 class Host(models.Model): ###nid 设置为自增,并设置为主键,db_index 为索引 nid = models.AutoField(primary_key=True,db_index=True) hostname = models.CharField(max_length=32) ip = models.GenericIPAddressField(max_length=32,db_index=True) ssh_port = models.IntegerField() ##service_id 简称 sid ,创建约束,表示,这个主机应该分给某个服务, # 此处的sid应该与Service 表的自带的id对应 sid = models.ForeignKey('Service',to_field='id') ##应用表,所属应用 class Application(models.Model): name = models.CharField(max_length=32) ##创建一对多的表,hobj对应host表,aobj对应Application表,两个值都为对象(queryset) class HostToApp(models.Model): hobj = models.ForeignKey('Host',to_field='nid') ##与host表建立约束,hobj的值为一个对象 aobj = models.ForeignKey('Application',to_field='id') ###与Application表建立约束,aobj的值为一个对象

方式二:django自动创建关系表(在一张表内创建和多个表的约束关联)
首先将
class HostToApp(models.Model): hobj = models.ForeignKey('Host',to_field='nid') aobj = models.ForeignKey('Application',to_field='id')
注释,然后执行:

会自动删除表
创建关联表(只能创建两列,最多三列(包含默认生成的id列),如果加额外的列做不到)


两个类,生成了3张表,但是无法对第三张表进行操作,多对多创建实例:

生成application 和application_r表以后


视图函数views.py
def app(request): if request.method == "GET": app_list= models.Application.objects.all() # for row in app_list: # print (row.id) ##row.r.all() 获取的是host表的对象(queryset)[row.id,row.name,row.r.all()] host_list_query = models.Host.objects.all() #c = models.Application.objects.all().values_list('name') 获取name列的值 return render(request,'app.html',{'app_list':app_list,'host_list_query':host_list_query}) elif request.method == "POST": app_name = request.POST.get('app_name') hostlist = request.POST.getlist('host_list') #print (app_name,hostlist) if app_name in models.Application.objects.all().values_list('name')[0]: obj = models.Application.objects.filter(name=app_name) #QuerySet for i in obj: print (i.id,i.name,i.r) i.r.add(*hostlist) return redirect('/cmdb/app/') else: # <class 'cmdb.models.Application'> obj = models.Application.objects.create(name=app_name) print (type(obj)) obj.r.add(*hostlist) return redirect('/cmdb/app/')

app.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .hide{ display: none; } .shade{ top:0; left: 0; right: 0; position: fixed; bottom: 0; background-color: green; opacity: 0.6; z-index: 100; } .add-host{ top:25%; height: 300px; width: 400px; background-color: white; border:1px; position: fixed; left:50%; z-index: 101; margin-left: -200px; } {# .hostname{#} {# display: inline-block;#} {# padding: 1px;#} {# border:1px;#} {# background-color: palevioletred;#} {# }#} </style> </head> <body> <h1>应用列表</h1> <div> <input id='add_host' type="button" value="添加"/> </div> <div> <table border="1" style="text-align: center;"> <thead> <tr> <td>应用名称</td> <td>应用主机列表</td> </tr> </thead> <tbody> {% for row in app_list %} <tr> <td>{{ row.name }}</td> <td class="hostname"> {% for i in row.r.all %} <span>{{ i.hostname }}</span> {% endfor %} </td> </tr> {% endfor %} </tbody> </table> </div> <div class="shade hide"></div> <div class="add-host hide"> <form id='add_form' action="/cmdb/app/" method="POST"> <div> <input id='app_name' type="text" name="app_name" placeholder="应用名称"/> </div> <div> <select name="host_list" multiple> {% for row in host_list_query %} <option value="{{ row.nid }}">{{ row.hostname }}</option> ##注意,此处为host表的内容,nid为自增id,不要写成id {% endfor %} </select> </div> <input id='submit' type="submit" value="提交" /> <input id='submit_ajax' type="submit" value="ajax提交" /> <input id='cancel' type="button" value="取消" /> </form> </div> <script src="/static/jquery-3.2.1.js"></script> <script> $(function () { $('#add_host').click(function () { $('.shade,.add-host').removeClass('hide') }); }); $(function () { $('#submit,#cancel').click(function () { $('.shade,.add-host').addClass('hide') }) }); $('#submit_ajax').click(function () { $.ajax({ url:'/cmdb/app/', data:$('#add_form').serialize(), type:'POST', traditional:true, /*基于列表方式传值*/ dataType:'JSON', success:function (data) { } }) }) </script> </body> </html>

浙公网安备 33010602011771号