首页 > 代码库 > 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多对多