Django框架学习笔记(17.多对多简易实例)

创建多对多:

方式一(自定义关系表)

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


class Application(models.Model):
    name = models.CharField(max_length=32)

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)

操作:
models.HostToApp.objects.create(hobj_id=1,aobj_id=2)

方式二(自动创建关系表)(缺点是不能创建多个表的多对多)

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


class Application(models.Model):
    name = models.CharField(max_length=32)
    r = models.ManyToManyField("Host")
 
#自动创建了一个app01_application_r表
#无法直接对第三张表操作,可以间接操作
obj = Application.objects.get(id=1)
obj.r.add(1)
#在第三张表里面增加一个1对应1
obj.r.remove(1)
obj.r.clear()    #清除id=1的全部
obj.r.set()      #更改



接下来在以前的基础上写一个简单的(采用上面的方式二):

views.py部分(加入相应url对应关系):

def app(request):
    if request.method == "GET":
        app_list = models.Application.objects.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')
import json
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))


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: chartreuse;
        }
        .hide {
            display: none;
        }

        .shade {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: black;
            opacity: 0.6;
            z-index: 100;
        }

        .add-model, .edit-model {
            position: fixed;
            height: 300px;
            width: 400px;
            top: 100px;
            left: 50%;
            z-index: 101;
            border: 1px solid red;
            background-color: white;
            margin-left: -200px;
        }

    </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-model hide">
    <form id="add_form" method="POST" action="/app">
        <div class="group">
            <input id="app_name" type="text" placeholder="应用名" name="app_name"/>
        </div>
        <div>
            <select 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-model hide">
    <form id="edit_form" method="POST" action="/host">
        <input type="text" name="nid" 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">确认编辑</a>
    </form>
</div>
</table>
<script src="/static/jquery1.js"></script>
<script>
    $(function () {
        $('#add_app').click(function () {
            $('.shade,.add-model').removeClass('hide')
        });
        $('#cancel').click(function () {
            $('.shade,.add-model').addClass('hide')
        });
        $('#add_submit_ajax').click(function () {
            $.ajax({
                url: 'ajax_add_app',
                data: $('#add_form').serialize(),
                type: "POST",
                dataType:"JSON",
                traditional: true,
                success:function(obj){
                    //这里写入相关操作
                },
                error:function(){

                }
            })
        });
        $('.edit').click(function(){
            $('.edit-model,.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 = "new name"
            obj.save()
            obj.r.set([1,2,3,4])*/
        });

    })
</script>
</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值