1.多对多创建的应用场景:
在某表中创建一行数据是,有一个可以多选的下拉框
例如:创建用户信息,需要为用户指定多个爱好
2.创建方式:
方式一:自定义关系表,手动创建一张表用于关联其他多张表的关系
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(db_index=True)
port=models.IntegerField()
business=models.ForeignKey(to='Business',to_field='id')#business_id
class App(models.Model):
name=models.CharField(max_length=32)
class ConnHostApp(models.Model):
hobj=models.ForeignKey(to='Host',to_field='nid')
aobj=models.ForeignKey(to='ConnHostApp',to_field='id')
方式二:Django自动创建关系表
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharField(max_length=32,db_index=True)
ip=models.GenericIPAddressField(db_index=True)
port=models.IntegerField()
business=models.ForeignKey(to='Business',to_field='id')#business_id
class App(models.Model):
name=models.CharField(max_length=32)
r=models.ManyToManyField('Host')