多對多--ManyToMany
應用場景
在某表中創建一行數據時,有一個可以多選的下拉框(一對一是單選框)
例如:創建用戶信息,需要為用戶指定多個愛好
創建表
兩種方法,一個是利用Django自動為多對多創建關聯的第三張表,另一種是自己手動創建關系表。
NO.1
根據Django中的代碼,自動為多對多表創建一個第三張表對應關系
1
2
3
4
5
6
7
8
|
class
Host(models.Model):
hostname
=
models.CharField(max_length
=
32
)
port
=
models.IntegerField()
class
HostAdmin(models.Model):
username
=
models.CharField(max_length
=
32
)
email
=
models.CharField(max_length
=
32
)
host
=
models.ManyToManyField(Host)
|
NO.2
自定義多對多表,沒有ORM都是自己生成
models.py
1
2
3
4
5
6
7
8
9
10
11
12
|
class
Host1(models.Model):
hostname
=
models.CharField(max_length
=
32
)
port
=
models.IntegerField()
class
HostAdmin1(models.Model):
username
=
models.CharField(max_length
=
32
)
email
=
models.CharField(max_length
=
32
)
host
=
models.ManyToManyField(Host1, through
=
'HostRelation'
)
class
HostRelation(models.Model):
c1
=
models.ForeignKey(Host1)
c2
=
models.ForeignKey(HostAdmin1)
|
view.py
1
2
3
4
5
6
7
8
9
|
#多對多自定義創建表
models.HostRelation.objects.create(
c1
=
models.Host1.objects.get(
id
=
1
),
c2
=
models.HostAdmin1.objects.get(
id
=
2
)
)
models.HostRelation.objects.create(
c1_id
=
2
,
c2_id
=
1
)
|
創建數據
1
2
3
4
5
6
7
|
初始化數據
models.Host.objects.create(hostname
=
'c1'
,port
=
80
)
models.Host.objects.create(hostname
=
'c2'
,port
=
80
)
models.Host.objects.create(hostname
=
'c3'
,port
=
80
)
models.HostAdmin.objects.create(username
=
'root'
,email
=
'1@live.com'
)
models.HostAdmin.objects.create(username
=
'dali'
,email
=
'dali@live.com'
)
models.HostAdmin.objects.create(username
=
'haojie'
,email
=
'haojie@live.com'
)
|
添加數據
1
2
3
4
5
6
7
8
9
10
11
12
|
#正向添加
#目的,給大力分配兩個主機的管理權限
#1、獲取大力用戶
admin_obj
=
models.HostAdmin.objects.get(username
=
'dali'
)
#2、獲取指定的兩個主機
host_list
=
models.Host.objects.
filter
(id__lt
=
3
)
#3、將兩個主機和大力添加到第三張對應表中
admin_obj.host.add(
*
host_list)
#反向添加
host_obj
=
models.Host.objects.get(
id
=
3
)
admin_list
=
models.HostAdmin.objects.
filter
(id__gt
=
1
)
host_obj.hostadmin_set.add(
*
admin_list)
|
查詢數據
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#查詢數據
#第一種方式
#正向查
admin_obj
=
models.HostAdmin.objects.
all
(
id
=
1
)
for
item
in
admin_obj:
item.host.
all
()
#反向查
host_obj
=
models.Host.objects.get(
id
=
1
)
host_obj.hostadmin_set.
all
()
#第二種方式
relation_list
=
models.HostRelation.objects.
all
()
relation_list
=
models.HostRelation.objects.
filter
(c2__username
=
'dali'
)
for
item
in
relation_list:
print
item.c1.hostname
print
item.c2.username
|