看一下自己的models文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class
HostList(models.Model):
ip
=
models.IPAddressField(unique
=
True
, verbose_name
=
u
'IP地址'
)
hostname
=
models.CharField(max_length
=
30
, verbose_name
=
u
'主机名'
)
group
=
models.ManyToManyField(
'Group'
, null
=
True
, blank
=
True
,verbose_name
=
u
'组名'
)
application
=
models.CharField(max_length
=
20
, verbose_name
=
u
'应用'
)
bianhao
=
models.CharField(max_length
=
30
, verbose_name
=
u
'编号'
)
idc_name
=
models.CharField(max_length
=
40
,null
=
True
,blank
=
True
, verbose_name
=
u
'所属机房'
)
def
__unicode__(
self
):
return
self
.ip
class
Group(models.Model):
name
=
models.CharField(max_length
=
50
,unique
=
True
)
def
__unicode__(
self
):
return
self
.name
|
这两个表组成多对多关系,自然而然就产生了第三个对应记录ID值的表:
1
2
3
4
5
6
7
8
9
|
mysql> show tables;
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
| Tables_in_cmdb |
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
| app_group |
| app_hostlist |
| app_hostlist_group |
可以看多多出了一个app_hostlist_group的表:
|
1
2
3
4
5
6
7
8
9
10
|
mysql> select
*
from
app_hostlist_group;
+
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
+
|
id
| hostlist_id | group_id |
+
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
+
|
13
|
18
|
1
|
|
8
|
17
|
2
|
|
3
|
16
|
2
|
|
12
|
14
|
2
|
|
11
|
19
|
1
|
+
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
+
|
映射了id的对应关系;关于查询的两种方式:
第一:从前端返回的一个组名,通过这个组查找到HostList表里面的所有IP:
id = request.GET.get('id')
group_name = Group.objects.get(id=id)
all_ip = group_name.hostlist_set.all()
print all_ip
查看后台代码执行效果:(结果主要有HostList的return self.ip决定)
1
2
|
[
01
/
Sep
/
2015
07
:
50
:
04
]
"GET /group/ HTTP/1.1"
200
24954
[<HostList:
192.168
.
63.114
>, <HostList:
192.168
.
63.63
>]
|
本文转自 小罗ge11 51CTO博客,原文链接:http://blog.51cto.com/xiaoluoge/1691303,如需转载请自行联系原作者