django ORM 多对多的主机管理

作者: print("") 分类: python 发布时间: 2018-07-21 21:34

django ORM 多对多的主机管理

主要是对ORM 不是太好理解。后端一点都不是很难写,就是前段 的ajax 和JQ 很烦人,上班的时候写的发毛

进入主题吧=。-  

表的结构如下:

from django.db import models

# Create your models here.

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("Business",to_field='id',on_delete=models.CASCADE,)


class Business(models.Model):
    # 业务线
    caption=models.CharField(max_length=32)
    code=models.CharField(max_length=32,null=True,default='SA')




class Application(models.Model):
    #应用表
    name=models.CharField(max_length=32)
    r=models.ManyToManyField("Host")
#
# class HosttoApp(models.Model):
#     # hobj 是对host的表建立关系  aobj 是跟app这个表建立关系
#     # hobj 1~10  aobj  1~2
#     hobj=models.ForeignKey("Host",to_field="nid",on_delete=models.CASCADE,)
#     aobj=models.ForeignKey("Application",to_field="id",on_delete=models.CASCADE,)
#

这次用的是django 提供的第三张表的方式

核心代码很简单

from django.shortcuts import render,redirect,HttpResponse

# Create your views here.
from app01 import models

import json

def test_ajax(request):
    # 返回的是字典格式
    ret={'status':True,'error':None,'data':None}
    try:
        # 获取客户端发送的post 数据
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        print(h)
        #判断host 是否为空和大于5
        if h and  len(h) > 5:
            print("ja")
            # 新建
            models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b)
            return HttpResponse('OK')
        else:
            # 写入到字典中
            ret['status']=False
            ret['error']="太短了"

    except Exception as e:
        # 返回字典
        ret['status'] = False
        ret['error'] = "请求错误"
    return HttpResponse(json.dumps(ret))

def business(request):
    # 业务线的获取

    v1=models.Business.objects.all()
    # QuerySet
    #[ ]
    #[obj1(id,caption,code),obj2(id,caption,code),obj3(id,caption,code)]
    v2 = models.Business.objects.all().values('id','caption')
    # QuerySet
    # [ ]
    # [{'id':1,'caption':xxx}]
    v3 = models.Business.objects.all().values_list('id', 'caption')
    # QuerySet
    # [ ]
    # [(1,运维),(2.开发),(3,测试)]

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




def host(requests):
    # host 页面的返回数据
    if requests.method=='GET':
        v1=models.Host.objects.filter(nid__gt=0)
        v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','ip','port','b_id','b__caption','b__code')
        v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','ip','port','b_id','b__caption','b__code')

        b_list=models.Business.objects.all()

        return render(requests,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list})

    # POST 的返回数据
    elif requests.method=='POST':
        h=requests.POST.get('hostname')
        i=requests.POST.get('ip')
        p=requests.POST.get('port')
        b=requests.POST.get('b_id')
        print(h,i,p,b)
        #host 页面新建数据
        models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b)
        return redirect('/host/')

def app(request):
    if request.method=='GET':
        app_list=models.Application.objects.all()
        # for row in app_list:
        #     print(row.name)
        #     print(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_list')
        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}
    try:
        app_name=request.POST.get('app_list')
        host_list= request.POST.getlist('host_list')
        print(app_name)
        if app_name and host_list:
            obj = models.Application.objects.create(name=app_name)
            obj.r.add(*host_list)
        else:
            ret['status'] = False
            ret['error'] = "不能为空"
        return HttpResponse(json.dumps(ret))

    except Exception as e:
        # 返回字典
        ret['status'] = False
        ret['error'] = "请求错误"
    return HttpResponse(json.dumps(ret))



def ajax_submit_edit(request):
    ret = {'status': True, 'error': None, 'data': None}
    try:
        app_name = request.POST.get('app_list2')
        host_list = request.POST.getlist('host_list')
        aid=request.POST.get('app_id3')
        print(app_name, host_list, aid)
        if app_name and host_list:
           if app_name==aid:
               obj=models.Application.objects.get(id=aid)
               obj.r.set(host_list)
           else:
               obj = models.Application.objects.get(id=app_name)
               obj.r.set(host_list)
        else:
            ret['status'] = False
            ret['error'] = "不能为空"
        return HttpResponse(json.dumps(ret))

    except Exception as e:
        # 返回字典
        ret['status'] = False
        ret['error'] = "请求错误"
    return HttpResponse(json.dumps(ret))

'''
def userdel(request,app_id):
    ret = {'status': True, 'error': None, 'data': None}
    try:
        if app_id:
            obj=models.Application.objects.filter(id=app_id).first()
            if obj.name:
                print(obj.name,obj.r.all())

    except Exception as e:
    # 返回字典
        ret['status'] = False
        ret['error'] = "请求错误"
    return HttpResponse('OK')
'''
def userdel(request,nid):
    ret = {'status': True, 'error': None, 'data': None}
    try:
        if nid:
            obj = models.Application.objects.filter(id=nid).first()
            if obj.name:
                obj.r.clear()
                models.Application.objects.filter(id=nid).delete()

            else:
                ret['status'] = False
                ret['error'] = "删除失败"
    except Exception as e:
        # 返回字典
        ret['status'] = False
        ret['error'] = "请求错误"
    return redirect('/app')


def userinfo(request,nid):
    app=models.Application.objects.filter(id=nid).first()
    if app:
        app_name=app.name
        host=app.r.all()

        return render(request,'userinfo.html',{'app_name':app_name,'host':host})
    else:
        return render(request, '404.html')


页面操作如下:

可以实现最简单的增删查改

添加:

删除:

编辑

还有一个主机的这种的没写:只是 写了一个最基本的

源代码如下:

http://www.o2oxy.cn/wp-content/uploads/2018/07/多对多管理系统.zip

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

说点什么

avatar
  Subscribe  
提醒