1.多对多关系表的创建:
我们会发现无论是一对一、一对多还是多对多关系表基本大同小异,变化的是 models的属性名文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
格式:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
class A(models.Model):文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
……文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
class B(models.Model):文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
……文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
绑定变量名=models.ManyToManyField(A)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
2.示例:创建学生与课程之间的多对多关系表:
我们仍旧是创建两个类,分别是Student和Course,并且在Course类下建立多表关联。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
3.多对多关系数据新增:
多对多关系数据新增与前两者是有差异的,分两种:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
1)先新增Student类的数据然后关联Course:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
格式:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
变量名=A.objects.create(字段='值')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
变量名=变量名.B类名小写_set.create(字段='值')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
2)先新增Course类的数据然后关联Student:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
变量名=B.objects.create(字段='值')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
变量名=变量名.绑定变量名.create(字段='值')文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
4.多对多关系数据库查询:
多对多关系数据查询与一对多的数据查询是一样的:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html