django - 查询数据
django 中的模型管理器 objects
一、django中 objects/queryset 常见的查询方法
- get(query) : 只能查询单条记录,并且返回的是一个模型对象
- 只能查单条数据
- 如果返回多条,则抛出 MultipleObjectsReturned
- 如果没查到数据, 则抛出 DoesNotExist
- first() : 返回满足条件的第一条记录, 返回的是一个模型对象
- filter(query): 返回的是多条记录,并且返回的是 一个 queryset 对象
- exclude(query): 返回的是多条记录,返回的是一个 queryset 对象,查询不满足条件的数据
- all() : 返回所有满足条件的记录,返回一个 queryset 对象
- count() : 返回所有满足条件的记录数
二、query 条件的常见操作,相当于 where 语句
1. MySQL支持的 关系查询 >, >=, <, <=, ==, !=
mysql | django |
---|---|
> | __gt= |
>= | __gte= |
< | __lt= |
<= | __lte= |
== | __exact= |
!= | exclude() |
select * from 表 where stuNo > 3
=> Student.objects.filter(stuNo__gt=3)
2. MySQL 支持的 模糊查询 like => %(匹配多个)_(只匹配一个)
django | 解释 |
---|---|
__contains= | 是否包含某一个元素 |
__icontains= | 是否包含某一个元素,且忽略大小写 |
__startswith= | 以什么开头 |
__istartswith= | 以什么开头,且忽略大小写 |
__endswith= | 以什么结尾 |
__iendswith= | 以什么结尾,且忽略大小写 |
3. MySQL 支持的区间查询
MySQL | django |
---|---|
between … and | __range=元组,元组里面有2个值,小的在前,大的在后 |
Student.objects.filter(stuNo__range=(3,5))
4. MySQL 支持的 in 查询(枚举查询)
select * from 表 where stuNo in (3,4,5)
=> Student.objects.filter(stuNo__in=[3,4,5])
5. and or 的 逻辑查询
select * from 表 where name ='张三' and sex = 1
= > Student.objects.filter(name="张三", sex="1")
如果要想实现 or 查询,需要引入 Q:from django.db.models import Q
Q 支持 and 和 or 查询
select * from 表 where name ='张三' and sex = 1
=>Student.objects.filter( Q(name="张三") & Q(sex="1") )
select * from 表 where name = '张三' or sex = 1
=>Student.objects.filter( Q(name="张三") | Q(sex="1") )
查询(姓名=张三 且 性别=男)或 (性别=保密)的数据
Student.objects.filter( Q(name="张三", sex="1") | Q(sex="3") )
6. 空值查询:
select * from 表 where birth is null
=> Student.objects.filter(birth__isnull=True)
三、django 中对查询结果的排序
objects/queryset 拥有的方法:order_by(*fields)
select * from 表 order by stuNo desc, name asc
=> Student.objects.all().order_by("-stuNo", "name")