首页 > 代码库 > django多对多
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多对多
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。