[Django学习]查询过滤器(lookup types)

1.exact

exact用于精确匹配字段的值。适用于需要精确查找某个字段值的场景。

python 复制代码
Book.objects.filter(title__exact='Harry Potter')

上面的查询会查找标题完全为"Harry Potter"的书籍。

2.iexact

iexact忽略大小写地精确匹配字段的值。适用于需要忽略大小写进行精确匹配的场景。

python 复制代码
Book.objects.filter(title__iexact='harry potter')

这将查找标题在忽略大小写的情况下完全匹配"harry potter"的书籍。

3.contains

contains用于查找字段包含特定子字符串的记录,适用于部分匹配查询。

python 复制代码
Book.objects.filter(title__contains='Harry')

查找标题包含"Harry"的书籍。

4.icontains

icontains忽略大小写查找字段包含特定子字符串的记录。

python 复制代码
Book.objects.filter(title__icontains='harry')

5.startswith

查找以特定字符串开头的记录。

python 复制代码
Book.objects.filter(title__startswith='Harry')

6.istartswith

忽略大小写

python 复制代码
Book.objects.filter(title__istartswith='harry')

7. endswith

endswith用于查找以特定字符串结尾的记录。

8. iendswith

iendswith忽略大小写地查找以特定字符串结尾的记录。

9. in

查找字段值在给定列表中的记录,适用于批量匹配查询(数组)。

python 复制代码
Book.objects.filter(title__in=['Harry Potter', 'The Hobbit'])

只要标题是在给定的数组中,就会把这条记录拿出来

10. gt

查找字段值大于特定值的记录。

python 复制代码
Book.objects.filter(price__gt=5)

查找价格严格大于5块钱的书

11. gte

查找字段值大于或等于特定值的记录。

12./13. lt/lte

lt用于查找字段值小于/小于等于特定值的记录。

14. range

range用于查找字段值在特定范围内的记录。

python 复制代码
Book.objects.filter(price__range=(1, 10))

查找价格在1到10元的书本,range可以和上文的gt/gte、lt/lte搭配使用,如下

python 复制代码
        if datas.get("countFlag") == "on":
            if datas.get("count") == "1":
                query &= Q(counts__range=(0, 10))
            elif datas.get("count") == "2":
                query &= Q(counts__range=(10, 50))
            elif datas.get("count") == "3":
                query &= Q(counts__range=(50, 100))
            elif datas.get("count") == "4":
                query &= Q(counts__gte=100)

15. date

date用于精确匹配日期字段的值。

python 复制代码
Book.objects.filter(publish_date__date='2022-01-01')

16. year

year用于匹配特定年份的日期字段。

python 复制代码
Book.objects.filter(publish_date__year=2022)

17./18. month/day

用法同上

19. week_day

week_day用于匹配特定星期几的日期字段。注意:1代表星期天,2代表星期一,以此类推。

python 复制代码
Book.objects.filter(publish_date__week_day=2)

这个语句查询发布日期是在周一的书本

20. isnull

查找字段值为空的记录。如下查找作者字段为空的书籍。

python 复制代码
Book.objects.filter(author__isnull=True)

21. regex

正则表达式匹配字段值。

python 复制代码
Book.objects.filter(title__regex=r'^Harry')

查找标题以"Harry"开头的书籍。

22. iregex

iregex忽略大小写地正则表达式匹配字段值。

相关推荐
ㄟ留恋さ寂寞1 分钟前
html如何修改备注
jvm·数据库·python
2401_884454154 分钟前
c++如何读取YAML格式配置文件_yaml-cpp库快速入门【详解】
jvm·数据库·python
2301_7756398917 分钟前
mysql升级时如何使用Ansible进行自动化部署_mysql自动化管理
jvm·数据库·python
WUYOUGYLU22 分钟前
第一次买云服务器,最该先看什么?
数据库
CLX050531 分钟前
怎样设置外键的更新级联操作_ON UPDATE CASCADE配置
jvm·数据库·python
李少兄33 分钟前
高性能MySQL实战:应用层关联查询的深度优化
数据库·mysql
zjy277771 小时前
SQL Server如何实现编写表与字段注释_Navicat兼容操作步骤
jvm·数据库·python
m0_702036531 小时前
CSS移动端实现响应式导航菜单_利用媒体查询切换显示隐藏状态
jvm·数据库·python
m0_596749091 小时前
Go语言怎么用Jaeger_Go语言Jaeger链路追踪教程【实用】
jvm·数据库·python
2501_901006471 小时前
Golang Gin如何定义路由和路由组_Golang Gin路由教程【实用】
jvm·数据库·python