多对多数据库的建立
class Host(models.Model): nid = models.AutoField(primary_key=True) #自增id hostname = models.CharField(max_length=32, db_index=True) ip = models.GenericIPAddressField(db_index=True) port = models.IntegerField(max_length=32) b = models.ForeignKey(to='Business', to_field='id', on_delete=models.CASCADE)class Application(models.Model): name = models.CharField(max_length=32, null=True) r = models.ManyToManyField('Host')
通过models.ManyToManyField 创立 Host 与 Application的连接
v1 = models.Application.object.all()
v1.name
for i in v1.r.all():
i.hostname
增加:
obj = models.Application.object.create(name)
obj.r.add(hostname)
改:
obj = models.Application.object.get(id=nid)obj.name = name
obj.r.set(hostname)
删
obj = models.Application.object.get(id=nid)
models.Application.object.delete(id=nid)
obj.r.clear()