码迷,mamicode.com
首页 > 其他好文 > 详细

django多对多

时间:2017-04-12 18:31:07      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:object   objects   自动   mode   color   self   bsp   protocol   ipaddress   

 

创建多对多

方式一:自定义关系表

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多对多

标签:object   objects   自动   mode   color   self   bsp   protocol   ipaddress   

原文地址:http://www.cnblogs.com/xone/p/6700661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!