标签:
在某表中创建一行数据时,有一个可以多选的下拉框(一对一是单选框)
例如:创建用户信息,需要为用户指定多个爱好
两种方法,一个是利用Django自动为多对多创建关联的第三张表,另一种是自己手动创建关系表。
根据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) |
自定义多对多表,没有ORM都是自己生成
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) |
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 |
标签:
原文地址:http://www.cnblogs.com/daliangtou/p/5423914.html