常用查询及表关系的实现
1. 常用查询
每一个 django 模型类, 都有一个默认的管理器 objects
QuerySet 表示数据库中对象的列表, 它可以有 0 到多个过滤器. 过滤器通过给定参数, 缩小查询范围.
QuerySet 等同于 select 语句, 过滤器是一个限制子句, 比如 where,limit.
all() 获取所有
Student.objects.all() #返回的是 queryset
获取第一条
Student.objects.first() #返回的是对象
获取最后一条
Student.objects.last() #返回的是对象
get(**kwargs) 根据给定的条件获取一个对象, 如果符合多个或没有就会报错
filter(**kwargs) 过滤, 根据参数提供的条件, 获取一个过滤器后的 QuerySet, 多个条件等同于 select 子句使用 and 连接, 关键字的参数的形参必须是模型中的字段名.
Student.objects.filter(name='张三').filter(sex=0)
exclude(**kwargs) 用法和 filter 一样, 作用相反, 它是排除
order(*fileds), 根据给定的字段排序
res.order_by('-age','name') #默认 asc, -age 代表反向排序
切片: 使用列表的切片语法操作 query, 除了不能用负索引, 其他都可以, 他等价于 LIMIT 与 OFFSET 子句
values(*fileds) 返回 queryset, 这个 queryset 返回的是一个字典列表, 参数 fields 指定了 select 中我们想要限制查询的字段. 返回的字典列表中, 只会包含我们指定的字段. 如果不指定, 包含所有字段.
res=Student.objects.values('name')
only(*fileds) 返回一个 queryset, 跟 values 一样, 区别在于这个 queryset 是对象列表, only 一定包含主键.
res=Student.objects.only('name')
defer(*fields) 用法与 only 相反
res=Student.objects.defer('sex')
多条件 OR 连接, 需要实现 OR 条件, 我们要使用 Q 对象
- from django.db.models import Q
- res=Student.objects.filter(Q(age=18)|Q(age=19)).only('name')
等价于下面的 sql:
- SELECT `teacher_student`.`id`, `teacher_student`.`name` FROM `teacher_student` WHERE
- (`teacher_student`.`age` = 18 OR `teacher_student`.`age` = 19)
查询条件:
exact 精确匹配
res=Student.objects.filter(name__exact='张三')
iexact 忽略大小写
- res=Student.objects.filter(name__iexact='张三')
- contains
- res=Student.objects.filter(name__contains='张三')
- icontains
- in
- res=Student.objects.filter(name__in=[18,20])
- gt (great than)
- gte (great than equal)
- res=Student.objects.filter(name__gte=18)
- lt (Less than)
- res=Student.objects.filter(name__lt=18)
- lte
startswith 以什么开始
- res=Student.objects.filter(name__startswith='张')
- istartswith
endwith 以什么结尾
iendwith
range 范围区间
- res=Student.objects.filter(name__range=(18,20))
- isnull
- res=Student.objects.filter(name__isnull=True)
语法都是 field__condition 是两个下划线
count 返回 queryset 的长度
聚合函数
- Avg
- # 计算同学们的年龄平均值
- res=Student.objects.aggregate(age_avg=Avg('age'))
Max 最大值
- # 找到年龄最大的学生
- res=Student.objects.aggregate(age_max=Max('age'))
Min 最小值
sum 求和
分组, 聚合, 分组需要结合 values,annotate 和聚合方法看下面的案例
- # 查询男生女生分别有多少人
- from django.db.models import Count
- res=Student.objects.values('sex').annotate(Count('sex'))
2. 常用模型字段类型
参考官方文档
https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-types
3. 表关系实现
django 中, 模型通过特殊的字段进行关系连接.
一对一
一对多
多对多
来源: http://www.bubuko.com/infodetail-3004620.html