多对多实例

程序目录

Models.py

from django.db import models
# Create your models here.
class Business(models.Model):
    #默认id
    caption=models.CharField(max_length=32)
    code=models.CharField(max_length=30,null=True,default='sa')

class Host(models.Model):
    nid=models.AutoField(primary_key=True)
    hostname=models.CharField(max_length=32,db_index=True)
    ip=models.GenericIPAddressField(protocol='ipv4',db_index=True)
    port=models.IntegerField()
    b=models.ForeignKey('Business',to_field='id',on_delete = models.CASCADE)
# , on_delete = models.CASCADE

class Application(models.Model):
    name=models.CharField(max_length=32)
    r=models.ManyToManyField('Host')

# class HostToApp(models.Model):
#     hobj=models.ForeignKey(to='Host',to_field='nid',on_delete = models.CASCADE)
#     aobj=models.ForeignKey(to='Application',to_field='id',on_delete = models.CASCADE)

Urls.py

"""
s14day20 URL Configuration
"""
from django.contrib import admin
from django.conf.urls import url
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^business/$', views.business),
    url(r'^host/$', views.host),
    url(r'^test_ajax$', views.test_ajax),
    url(r'^app$', views.app),
    url(r'^ajax_add_app$', views.ajax_add_app),
]

Views.py

from django.shortcuts import render,HttpResponse,redirect
from app01 import models
import json
# Create your views here.

def business(request):
    v1=models.Business.objects.all()
    # QuerySet
    #[obj(id,caption,code),obj...,obj...]

    v2=models.Business.objects.all().values('id','caption')
    # QuerySet
    # [{'id':1, 'caption':'运维部'},{'id':2, 'caption':'开发部'},{'id':3, 'caption':'市场部'}]

    v3=models.Business.objects.all().values_list('id','caption')
    # QuerySet
    # [(1,运维部),(2,开发),()]

    return render(request,'business.html',{'V1':v1,'V2':v2,'V3':v3})


# def host(request):
#     v1=models.Host.objects.filter(nid__gte=0)
#     for row in v1:
#         print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b,row.b.id,row.b.caption,row.b.code,sep=" ")
#
#     v2=models.Host.objects.filter(nid__gte=0).values('nid','hostname','b_id','b__caption')
#     # 跨表用双下划线__
#     # 字典类型 QuerySet:[{}]
#     # print(v2)
#     for row in v2:
#         print(row['nid'],row['hostname'],row['b_id'],row['b__caption'])
#
#     v3 = models.Host.objects.filter(nid__gte=0).values_list('nid', 'hostname', 'b_id', 'b__caption')
#     # 跨表用双下划线__
#     for row in v3:
#         print(row[0], row[1], row[2], row[3])
#
#     # return HttpResponse('Host')
#     return render(request, 'host.html', {'V1': v1,'V2':v2,'V3':v3})


def host(request):
    if request.method=="GET":
        v1=models.Host.objects.filter(nid__gte=0)
        v2=models.Host.objects.filter(nid__gte=0).values('nid','hostname','b_id','b__caption')
        v3 = models.Host.objects.filter(nid__gte=0).values_list('nid', 'hostname', 'b_id', 'b__caption')
        b_list=models.Business.objects.all()
        return render(request, 'host.html', {'V1': v1,'V2':v2,'V3':v3,'B_List':b_list})
    elif request.method=="POST":
        h=request.POST.get('hostname')
        i=request.POST.get('ip')
        p=request.POST.get('port')
        b=request.POST.get('b_id')
        models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b)
        return redirect('/host/')


def test_ajax(request):
    ret={'status':True,'error':None,'data':None}
    try:
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        if h and len(h)>5:
            models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b)
        else:
            ret['status']=False
            ret['error']="主机名太短了"
    except Exception as e:
        ret['status']=False
        ret['error']='请求错误'
    return HttpResponse(json.dumps(ret))      #传字符串 字典转换成字符串


def app(request):
    if request.method=="GET":
        app_list= models.Application.objects.all()
        # for row in app_list:
        #     print(row.name,row.r.all())

        host_list=models.Host.objects.all()
        return render(request,'app.html',{'App_List':app_list,'Host_List':host_list})

    elif request.method=="POST":
        app_name=request.POST.get('app_name')
        host_list=request.POST.getlist('host_list')
        # print(app_name,host_list)
        obj = models.Application.objects.create(name=app_name) #创建完之后会返回一个对象 对象就是刚增加的这条对象
        obj.r.add(*host_list)
        return redirect('/app')

def ajax_add_app(request):
    ret={'status':True,'error':None,'data':None}
    app_name = request.POST.get('app_name')
    host_list = request.POST.getlist('host_list')
    obj = models.Application.objects.create(name=app_name)  # 创建完之后会返回一个对象 对象就是刚增加的这条对象
    obj.r.add(*host_list)
    return HttpResponse(json.dumps(ret))



business.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>业务线列表(对象)</h1>
    <ul>
        {% for row in V1 %}
            <li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li>
        {% endfor %}
    </ul>

     <h1>业务线列表(字典)</h1>
    <ul>
        {% for row in V2 %}
            <li>{{ row.id }} - {{ row.caption }}</li>
        {% endfor %}
    </ul>

    <h1>业务线列表(元组)</h1>
    <ul>
        {% for row in V3 %}
            <li>{{ row.0 }} - {{ row.1 }}</li>
        {% endfor %}
    </ul>
</body>
</html>

 

 

Home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .shade{
            position: fixed;
            top:0;
            right:0;
            left:0;
            bottom:0;
            background: black;
            opacity:0.5;
            z-index: 9;
        }
        .add-modal,.edit-modal{
            position: fixed;
            height:500px;
            width:650px;
            top:300px;
            left:50%;
            z-index: 10;
            border:1px solid #eeeeee;
            background-color: white;
            margin-left: -320px;
        }
    </style>
</head>
<body>
    <h1>主机列表(对象)</h1>
    <div>
        <input id="add_host" type="button" value="添加">
    </div>
    <table border="1">
        <thead>
            <tr>
                <th>序号</th>
                <th>主机名</th>
                <th>IP</th>
                <th>端口</th>
                <th>业务线名称</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>

            {% for row in V1 %}
             <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                <td>{{ forloop.counter }}</td>
{#                 forloop.counter/counter0/revcounter/revcounter0/parentloop#}
{#                          1开始增  0开始增    倒序到1   倒序到0     取父循环#}
                <td>{{ row.hostname }}</td>
                <td>{{ row.ip }}</td>
                <td>{{ row.port }}</td>
                <td>{{ row.b.caption }}</td>
                <td>
                    <a class="edit">编辑</a> | <a class="delete">删除</a>
                </td>
             </tr>
            {% endfor %}

        </tbody>
    </table>

    <h1>主机列表(字典)</h1>
    <table border="1">
        <thead>
            <tr>
                <th>主机名</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in V2 %}
             <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                <td>{{ row.hostname }}</td>
                <td>{{ row.b__caption }}</td>
             </tr>
            {% endfor %}
        </tbody>
    </table>

    <h1>主机列表(元组)</h1>
    <table border="1">
        <thead>
            <tr>
                <th>主机名</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in V3 %}
             <tr hid="{{ row.0}}" bid="{{ row.2 }}">
                <td>{{ row.1 }}</td>
                <td>{{ row.3 }}</td>
             </tr>
            {% endfor %}
        </tbody>
    </table>

    <div class="shade hide"></div>



    <div class="add-modal hide">
        <form action="/host/" method="post">
        <div class="group">
            <input id="host" type="text" placeholder="主机名" name="hostname">
        </div>
        <div>
            <input id="ip" type="text" placeholder="IP" name="ip">
        </div>
        <div>
            <input id="port" type="text" placeholder="端口" name="port">
        </div>
        <div class="group">
            <select id="sel" name="b_id">
                {% for op in B_List %}
                <option value="{{ op.id }}">{{ op.caption }}</option>
                {%endfor %}
            </select>
        </div>

        <input type="submit" value="提交"/>
        <a id="ajax_submit" style="display: inline-block;padding: 5px;background-color: blue;color:white;">悄悄提交</a>
        <input id="cancel" type="button" value="取消">
        <span id="error_msg" style="color: red;"></span>
        </form>
    </div>


    <div class="edit-modal hide">
        <form id="edit_form" action="/host/" method="post">
            <input type="text" name="hid" style="display: none">
            <input  type="text" placeholder="主机名" name="hostname">
            <input  type="text" placeholder="IP" name="ip">
            <input  type="text" placeholder="端口" name="port">
            <select  name="b_id">
                {% for op in B_List %}
                <option value="{{ op.id }}">{{ op.caption }}</option>
                {%endfor %}
            </select>
        <a id="ajax_submit_edit" style="display: inline-block;padding: 5px;background-color: blue;color:white;">确认编辑</a>
        </form>
    </div>


    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {
            $('#add_host').click(function () {
                $('.shade, .add-modal').removeClass('hide');
            });
            $('#cancel').click(function () {
                $('.shade, .add-modal').addClass('hide');
            });
            $('#ajax_submit').click(function () {
                $.ajax({
                    url:"/test_ajax",
                    type:'POST',
                    data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
                    success:function (data) {
                        var obj=JSON.parse(data);
                        if(obj.status){
                            location.reload();
                        }else{
                            $('#error_msg').text(obj.error);
                        }
                    }
                })
            });

            $('.edit').click(function () {
                $('.shade,.edit-modal').removeClass('hide');
                var bid= $(this).parent().parent().attr('bid');
                var hid=$(this).parent().parent().attr('hid');
                $('#edit_form').find('select').val(bid);
                $('#edit_form').find('input[name="hid"]').val(hid)
                //修改操作
                $.ajax({
                    data:$('#edit_form').serialize()
               })
                //models.Host.object.filter(nid=nid).update()
            })
        })
    </script>
</body>
</html>
{#字典在json的时候可以.点去取#}

 

 

App.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .host-tag{
            display: inline-block;
            padding: 3px;
            border:1px solid red;
            background-color: burlywood;
        }
        .hide{
            display: none;
        }
        .shade{
            position: fixed;
            top:0;
            right:0;
            left:0;
            bottom:0;
            background: black;
            opacity:0.5;
            z-index: 9;
        }
        .add-modal,.edit-modal{
            position: fixed;
            height:500px;
            width:650px;
            top:300px;
            left:50%;
            z-index: 10;
            border:1px solid #eeeeee;
            background-color: white;
            margin-left: -320px;
        }
    </style>
</head>
<body>
    <h1>应用列表</h1>
    <div>
        <input id="add_app" type="button" value="添加">
    </div>
    <table border="1">
        <thead>
            <tr>
                <td>应用名称</td>
                <td>应用主机列表</td>
            </tr>
        </thead>
        <tbody>
            {% for app in App_List %}
                <tr aid="{{ app.id }}">
                    <td>{{ app.name }}</td>
                    <td>
                        {% for host in app.r.all %}
                            <span class="host-tag" hid="{{ host.nid }}" >{{ host.hostname }}</span>
                            {% endfor %}
                    </td>
                    <td>
                        <a class="edit">编辑</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>


    <div class="shade hide"></div>


    <div class="add-modal hide">
        <form id="add_form" action="/app" method="post">
        <div class="group">
            <input id="app_name" type="text" placeholder="应用名称" name="app_name">
        </div>

        <div class="group">
            <select id="host_list" name="host_list" multiple>
                {% for op in Host_List %}
                    <option value="{{ op.nid }}">{{ op.hostname }}</option>
                {%endfor %}
            </select>
        </div>

        <input type="submit" value="提交"/>
        <input id="add_submit_ajax" type="button" value="Ajax提交"/>
        </form>
    </div>


    <div class="edit-modal hide">
        <form id="edit_form" action="/host/" method="post">
            <input type="text" name="hid" style="display: none">
            <input  type="text" placeholder="应用名称" name="app">
            <select  name="host_list" multiple>
                {% for op in Host_List %}
                    <option value="{{ op.nid }}">{{ op.hostname }}</option>
                {%endfor %}
            </select>
        <a id="ajax_submit_edit" style="display: inline-block;padding: 5px;background-color: blue;color:white;">确认编辑</a>
        </form>
    </div>

 <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {
            $('#add_app').click(function () {
                $('.shade, .add-modal').removeClass('hide');
            });
            $('#cancel').click(function () {
                $('.shade, .add-modal').addClass('hide');
            });
            $('#add_submit_ajax').click(function () {
                $.ajax({
                    url:'/ajax_add_app',
{#                    data:{'user':'root','host_list':[1,2,3,4]},#}
                    data:$('#add_form').serialize(),
                    type:"POST",
                    dataType:'JSON',
                    traditional:true,
                    success:function (obj) {
                        console.log(obj)
                    },
                    error:function () {
                    }
                })
            });

            $('.edit').click(function () {
                $('.edit-modal,.shade').removeClass('hide');

                var hid_list=[];
                $(this).parent().prev().children().each(function () {
                    var hid=$(this).attr('hid');
                    hid_list.push(hid)
                });
                $('#edit_form').find('select').val(hid_list);
                //如果发送到后台
                /*
                obj=models.Application.objects.get(id=aid);
                obj.name="name";
                obj.save();

                obj.r.set([1,2,3,4])
                */
            })
        })
    </script>
</body>
</html>
{#dataType:'JSON', 先序列化 成对象 obj#}
{#traditional:true, 传列表#}
{#$('#add_form').serialize()  取标签id=add_form下的所有值 app_name host_list#}

原文地址:https://www.cnblogs.com/leiwenbin627/p/11028862.html