一对多
在数据库中的体现
- 通过外键(Foreign Key)来体现一对多
- 在(多)的表中增加对(一)的外键
语法
- 使用外键(Foreign Key)在(多)的实体中增加
属性的=models.ForeignKey(Entry)
给图书增加出版社外键实战案例源码
查询
- 正向查询 通过Book查询Publisher
- 案例:查询id为1的书籍的信息
book=Book.objects.get(id=1)
publisher=book.publisher
正向查询实战案例源码
- 反向查询 通过Publisher查询Book
- Django会在(一)的实体中增加(多)的隐藏属性
- 关联对象小写_set
- 用于查询多的数据
- 注意,查询的时候,必须要在管理属性后面加参数
- all()或其他
反向查询实战案例源码
多对多关联
- 什么是多对多
- A表中的一条记录可以对应B表中的多条记录
- B表中的一条记录也可以对应A表中的多条记录
- 案例
- 在数据库中的体现
- 语法
- 允许在任何一个实体中增加操作
entry=models.ManyToManyField(Entry)
回忆
- Django数据库恢复备份状态的指令
python manage.py migrate index(应用名) 0001(状态id)
指定后台分组的实战源码
多对多查询
- 正向查询
- 通过作者(Author)表查询书籍(Book)表
author=Author.objects.get(id=1)
books=author.book.all()
通过关联属性.all()查询所有的数据
正向查询实战案例源码
- 反向查询
- 通过书籍(Book)表查询作者(Author)表
book=Book.objects.get(id=1)
authors=book.author_set.all()
反向查询实战案例元am
练习
- 创建Author和Publisher的多对多关系
- 查询李白所签约的所有出版社
- 查询北京大学出版社下的所有作者
实战案例源码
自定义查询对象 objects
- 声明类EntryManager,继承自models.Manager
class EntryManager(models.Manager):
def 函数名(self,自定义参数列表)
- 使用EntryManager覆盖models类中的objects
class Entry(models.Model):
objects=EntryManaer()
实战案例源码
练习
- 为Author指定自定义objects对象
- 为Book指定自定义的objects对象
查询书籍实战源码
年纪查询实战案例源码