创建多对多:
方式一:自定义关系表
class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business", to_field='id')
# 10
class Application(models.Model):
name = models.CharField(max_length=32)
# 2
class HostToApp(models.Model):
hobj = models.ForeignKey(to='Host',to_field='nid')
aobj = models.ForeignKey(to='Application',to_field='id')
# HostToApp.objects.create(hobj_id=1,aobj_id=2) 这里可以直接对第三张表直接操
方式二:自动创建关系表
class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business", to_field='id')
# 10
class Application(models.Model):
name = models.CharField(max_length=32)
r = models.ManyToManyField("Host") --------------> appname_application_r 表名
无法直接对第三张表进行操作
只能间接操作————————————————————
obj = models.Application.objects.get(id=1)
obj.name
# 第三张表操作:HostToApp table 基于id=1的Application添加对应关系
obj.r.add(1) 增
obj.r.add(2)
obj.r.add(2,3,4)
obj.r.add(*[1,2,3,4])
obj.r.remove(1) 删
obj.r.remove(2,4)
obj.r.remove(*[1,2,3])
obj.r.clear() 清除app_id =1 的列
obj.r.set([3,5,7]) 改 set将原来数据库中的关系先全部删除,在添加1-3,1-5,1-7
——————————————————————————
# 所有相关的主机对象“列表” QuerySet
obj.r.all() obj.filter() obj.first()
前端取
{%for app in app_list%}
<tr>
<td>{ {app.name}}</td>
<td>{ {app.r.all}}</td>
</tr>
{%endfor%}