day62

1.内容回顾
1. 外键的增删改查
1. 外键的语法
models.ForeignKey(to='', on_delete=models.CASCADE)
2. 外键查询的语法
book_obj.press --> 取到的是和我这本书关联的出版社对象
book_obj.press_id --> 数据库中实际保存的外键id
2. Django模板语言
1. if判断
{% if 条件 %}
...
{% else %}
...
{% endif %}
3. 昨天问题
1. ORM创建表的时候,出来俩选项
1) ...
2) ...

给数据库中已经存在的表添加另外一个字段,这个字段既没有默认值也不能为空
ORM就不知道数据库中已经存在的数据该怎么处理这个字段
2. Django请求的流程图
见群内截图


2. 今日内容
1. 多对多关系
作者 <--> 书籍
1. 表结构设计
1. SQL版
-- 创建作者表
create table author(
id int primary key auto_increment,
name varchar(32) not null
);

-- 创建作者和书的关系表
create table author2book(
id int primary key auto_increment,
author_id int not null,
book_id int not null,
constraint fk_author foreign key (author_id) references author(id) on delete cascade on update cascade,
constraint fk_book foreign key (book_id) references book(id) on delete cascade on update cascade
);

2. ORM版
1. 第一版:
自己创建第三张表
2. 第二版
让ORM帮我们创建第三张表
models.ManyToManyField()
3. 第三版
待补充...(ORM进阶操作的时候)
2. 作者的增删改查
1. 查询
author_obj.books --> 得到的只是一个关联关系,并不能拿到数据
author_obj.books.all() --> 得到和我这个作者关联的所有书籍对象列表
2. 添加
1. add()

3. 删除

4. 编辑
1. 模板语言中
{% if book in author.books.all %}
2. ORM编辑多对多
1. 不能直接操作第三张关系表
2. 借助ORM给提供的方法
1. all()
2. add(id1,id2)
3. set([id1, id2])
4. clear()
3. Django模板语言
1. for循环
1. forloop.last
{% if forloop.last %}
...
2. empty
{% for i in x %}
...
{% empty %}
...
{% endfor %}
4. 上传文件
form表单上传文件
原文地址:https://www.cnblogs.com/jerry-hou/p/12430469.html