django多对多
Posted xone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django多对多相关的知识,希望对你有一定的参考价值。
创建多对多
方式一:自定义关系表
class Host(models.Model): id = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32) ip = models.GenericIPAddressField(protocol=‘ipv4‘) port = models.IntegerField() b = models.ForeignKey(to=‘Business‘,to_field=‘id‘) def __str__(self): return self.hostname class Application(models.Model): name = models.CharField(max_length=32) class HostToApp(models.Model): hobj = models.ForeignKey(‘Host‘) aobj = models.ForeignKey(‘Application‘)
status = models.CharField(max_length=32)
方式二:自动创建表关系
class Host(models.Model): id = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32) ip = models.GenericIPAddressField(protocol=‘ipv4‘) port = models.IntegerField() b = models.ForeignKey(to=‘Business‘,to_field=‘id‘) def __str__(self): return self.hostname class Application(models.Model): name = models.CharField(max_length=32) r = models.ManyToManyField(to=‘Host‘) 无法直接对第三张表操作 obj = Application.objects.get(id=1) obj.name # 对第三张表操作 obj.r.add(1) #对第三张表添加application_id=1,host_id=1 obj.r.add(2,3) #对第三张表添加application_id=1,host_id=2;application_id=1,host_id=3 obj.r.add(*[1,2,3]) #对第三张表添加application_id=1,host_id=1;application_id=1,host_id=2;application_id=1,host_id=3 obj.r.remove(1) #删除第三张表application_id=1,host_id=1 obj.r.remove(2,3) #删除第三张表application_id=1,host_id=2;application_id=1,host_id=3 obj.r.remove(*[1,2,3]) #删除第三张表application_id=1,host_id=1;application_id=1,host_id=2;application_id=1,host_id=3 obj.r.clear() #删除第三张表的application_id=1的所有数据 obj.r.set([1,2,3]) #设置第三张表的application_id=1的数据为application_id=1,host_id=1;application_id=1,host_id=2;application_id=1,host_id=3其它数据删除
以上是关于django多对多的主要内容,如果未能解决你的问题,请参考以下文章