from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Host(models.Model):
    hostname=models.CharField(max_length=64)
    ip=models.GenericIPAddressField(unique=True)
    port=models.IntegerField(default=80)
    system_type_choices=(
        ('linux','LINUX'),
        ('Win64','WIN64'),
    )
    system_type=models.CharField(choices=system_type_choices,max_length=64)
    enable = models.BooleanField(default=True)
    create_date = models.DateTimeField()
    online_date = models.DateTimeField(auto_now_add=True)
    groups=models.ManyToManyField('HostGroup')
    idc = models.ForeignKey('IDC'    )

    def __unicode__(self):
        return self.hostname

class IDC(models.Model):
    name = models.CharField(max_length=64,unique=True)
    def __unicode__(self):
        return  self.name

class HostGroup(models.Model):
    name = models.CharField(max_length=64,unique=True)
    def __unicode__(self):
        return self.name

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=64,unique=True)
    host_groups = models.ManyToManyField('HostGroup',blank=True,null=True)
    hosts= models.ManyToManyField('Host',blank=True,null=True)

模糊查询,contains是包含
models.Host.objects.filter(system_type='LINUX',hostname__contains='o')
结果是一个列表  [<Host: localhost>, <Host: ubuntu>, <Host: jindie>]

精确查询,如果有出现多个,结果将报错
models.Host.objects.get(system_type='LINUX',hostname__contains='o')

id大于1的查询
models.Host.objects.filter(id__gt=1)

id in 列表查询
models.Host.objects.filter(id__in=[1,2,3,4,5])


创建第一种方法:models.Host.objects.create
import datetime
datetime.datetime.now()

(1) 写入数据库除了多对对 models.Host.objects.create( hostname
= 'OA', ip = '1.1.1.5', port = 80, system_type = 'WIN64', idc_id =1, #或者 idc = models.IDC.objects.get(name='万达机房') create_date = datetime.datetime.now(), online_date = datetime.datetime.now(), )
(2) 查询刚插入的数据信息(实例) h
= models.Host.objects.get(hostname='OA') (3) 查询多对多表的所有数据(实例) all_groups = models.HostGroup.objects.all() (4)把groups表的数据插入到Host表 h.groups.add(*[i.id for i in all_groups])
#删除  h.groups.remove(*[i.id for i in  all_groups])
#可以传入字典 h.groups.add(**{'a':1,'b':2})


#################################################### 创建的第二种方法,不查找,直接添加,models.Host

(1) h
= models.Host( hostname = 'OA', ip = '1.1.1.5', port = 80, system_type = 'WIN64', idc_id =1, create_date = datetime.datetime.now(), ) (2) h.save()
(3) all_groups
= models.HostGroup.objects.all()
(4)
h.groups.add(
*[i.id for i in all_groups])


############################################## update h.hostname
= 'feng' h.save models.Host.objects.filter().update(port=11111) ############################################## delete models.Host.objects.filter(hostname='OA').delete() ################################################# 跨表查询,从用户表查询 a = models.UserProfile.objects.last() a.host_groups.select_related() a.hosts_select_related() #################################### 判断用户是否登陆成功后,返回{{request.user}} {% if request.user.is_authenticated %} {{request.user}} {%else%} <a href="/login">退出</a> html编写 <div> {{ request.user.userprofile.hosts.select_related }} <ul> {% for group in request.user.userprofile.host_groups.select_related %} <li>{{ group.name }}</li> <ul> {% for host in group.host_set.select_related %} <li>{{ host.hostname }}----->{{ host.ip }}---{{ host.idc.name }}</li> {% endfor %} </ul> {% endfor %} </ul> ############################### views #!/usr/bin/env python #_*_ coding:utf-8 _*_ from django.shortcuts import render,redirect,HttpResponse,HttpResponseRedirect from django.template.context import RequestContext from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required #装饰器,不登陆,不能访问其他页面 import models @login_required() def host(request): return render(request,'host.html') def acc_login(request): ret = {'status':""} if request.method == 'POST': print request.POST username = request.POST.get('username',None) password= request.POST.get('password',None) user = authenticate(username=username,password=password)#验证用户名,密码 if user is not None: login(request,user) #如果不做这个动作,后台login还是没有登陆的,其他页面不能访问,其实就是差一个session return HttpResponseRedirect('/') else: ret['status']='用户名或者密码错误' return render(request, 'login.html', ret) else: return render(request,'login.html') @login_required() def index(request): return render(request,'index.html') @login_required() def asset(request): return render(request,'asset.html') @login_required() def acc_logout(request): logout(request) return HttpResponseRedirect('login.html')