建立多對多: 方式一:自定義關係表 class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32,db_index=True) ip = models.GenericIPAddressField(protocol="ipv4",db_index=True) port = models.IntegerField() b = models.ForeignKey(to="Business", to_field='id') # 10 class Application(models.Model): name = models.CharField(max_length=32) # 2 class HostToApp(models.Model): hobj = models.ForeignKey(to='Host',to_field='nid') aobj = models.ForeignKey(to='Application',to_field='id') # HostToApp.objects.create(hobj_id=1,aobj_id=2) 方式二:自動建立關係表 class Host(models.Model): nid = models.AutoField(primary_key=True) hostname = models.CharField(max_length=32,db_index=True) ip = models.GenericIPAddressField(protocol="ipv4",db_index=True) port = models.IntegerField() b = models.ForeignKey(to="Business", to_field='id') # 10 class Application(models.Model): name = models.CharField(max_length=32) r = models.ManyToManyField("Host") 沒法直接對第三張表進行操做 obj = Application.objects.get(id=1) obj.name # 第三張表操做 obj.r.add(1) obj.r.add(2) obj.r.add(2,3,4) obj.r.add(*[1,2,3,4]) obj.r.remove(1) obj.r.remove(2,4) obj.r.remove(*[1,2,3]) obj.r.clear() # 全部相關的主機對象「列表」 QuerySet obj.r.all()