Django多对多关联操作方法:建立、新增和查询

2022-10-1821:00:13后端程序开发Comments1,201 views字数 452阅读模式

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

Django多对多关联操作方法:建立、新增和查询

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

Django多对多关联操作方法:建立、新增和查询文章源自菜鸟学院-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

Django多对多关联操作方法:建立、新增和查询文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html

4.多对多关系数据库查询:

多对多关系数据查询与一对多的数据查询是一样的:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html

Django多对多关联操作方法:建立、新增和查询文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/28367.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/28367.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定