Django中多对多表的创建

方式一:自定义关系表

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()
			
	obj.r.set([3,5,7])
			
	# 所有相关的主机对象“列表” QuerySet
	obj.r.all()





你可能感兴趣的:(python-django)