django查询数据
django 中的模型管理器 objects
django中objects/queryset常见的查询方法有:
get(query) : 只能查询单条记录,并且返回的是一个模型对象
- 只能查单条数据
- 如果返回多条,则抛出 MultipleObjectsReturned
- 如果没查到数据, 则抛出 DoesNotExist
first() : 返回满足条件的第一条记录, 返回的是一个 模型对象 ,并且不用传参
filter(query): 返回的是多条记录,并且返回的是 一个 queryset 对象
exclude(query): 返回的是多条记录,返回的是一个 queryset对象,查询不满足条件的数据
all() : 返回所有满足条件的记录,返回一个 queryset对象
count() : 返回所有满足条件的记录数
values(*fields) : 按指定的字段进行数据的查询
distinct(): 对查询后的结果进行去除重复的内容
query 条件的常见操作,相当于 where 语句
- MySQL支持的 关系查询 > , >= , < , <= , == , !=
mysql | django |
---|---|
> | __gt= |
>= | __gte= |
< | __lt= |
<= | __lte= |
== | __exact= |
!= | exclude() |
Student.objects.filter(stuNo__gt=3)
相当于 select * from 表 where stuNo > 3
-
MySQL 支持的模糊查询 like % (匹配多个) _(只匹配一个)
MySQL 解释 _contains= : 是否包含某一个元素 _icontains= : 是否包含某一个元素,且忽略大小写 _startswith= : 以什么开头 _istartswith= : 以什么开头,且忽略大小写 _endswith= : 以什么结尾 _iendswith= : 以什么结尾,且忽略大小写 -
MySQL 支持的 区间查询
MySQL django
between … and __range=元组, 元组里面有2个值,小的在前,大的在后
Student.objects.filter(stuNo__range=(3,5))
- MySQL 支持的 in 查询(枚举查询)
select * from 表 where stuNo in (3,4,5)
Student.objects.filter(stuNo__in=[3,4,5])
- and or 的逻辑查询
Student.objects.filter(name=“张三”, sex=“1”)
– select * from 表 where name =‘张三’ and sex = 1
如果要想实现 or 查询,需要引入 Q
from django.db.models import Q
Q 支持 and 和 or 查询
Student.objects.filter( Q(name=“张三”) | Q(sex=“1”) )
– select * from 表 where name = ‘张三’ or sex = 1
Student.objects.filter( Q(name=“张三”) & Q(sex=“1”) )
– select * from 表 where name =‘张三’ and sex = 1
查询 (姓名=张三并且 性别=男) 或者 (性别=保密)的数据
Student.objects.filter( Q(name=“张三”, sex=“1”) | Q(sex=“3”) )
django中对查询结果的排序
objects/queryset 拥有的方法:
order_by(*fields)
Student.objects.all().order_by("-stuNo", “name”)
相当于 mysql 中
select * from 表 order by stuNo DESC , name asc