創建多對多
方式一:自定義關系表
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.name = 'new_name'
obj.save() 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其它數據刪除