Django-ORM
配置数据库
1 | DATABASES = { |
ORM操作
- 使用Django Shell
1 | python mange.py shell |
- 添加数据
1 | <Model>.objects.create(key=value, key=value, ...) |
- 查询数据
1 | # QuerySet可链式查询 |
1 | filter(attr1=value1, attr2=value2, ...) # select * from where attr1 = value1 and attr2 = value2 |
1 | # 查询谓词 __谓词 |
- 修改数据
1 | # 单个修改 |
1 | # 批量修改为同一值 |
删除数据
添加字段伪删除
1 | m = <Model>.objects.get() |
1 | ms = <Model>.objects.filter() |
F对象
考虑并发情况
若先获取,赋值再更新,出错
info.like = F(‘like’)+1
info.save
-> update info set like = like+1 where ?
1
2
3# 列出价格高于自己的书
from django.db.models import F
Book.objects.filter(price__gt=F('price'))Q对象
处理逻辑且&、逻辑或|、逻辑非~等操作
1
2from django.db.models import F
<Model>.objects.filter(Q()&Q()|~Q())聚合查询
整表聚合
1
2
3from djange.db.models import *
# Sum, Avg, Count, Max, Min
<Models>.ojects.aggregate(结果变量名=聚合类型(col)) -> dict分组聚合
1
2m = <Model>.objects.values(col1, col2, ...)
m.annotate(结果变量名=聚合类型(col)) -> QuerySet原生数据库操作
1
<Model>.objects.raw(sql) -> RawQuerySet # 只支持基础操作
1
2# 防注入
<Model>.objects.raw(sql, [value1, value2])1
2
3from django.db import connection
with connection.cursor() as cur:
cur.execte(sql, 拼接参数)关系映射
一对一
1 | class A(models.Model): |
- 一对多
1 | class A(models.Model): |
- 多对多
1 | # 需要依赖第三张表,Django无需手动创建 |
分页
1 | paginator = Paginator(object_list, per_page) |
1 | # page对象 |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.