[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忽略大小写地正则表达式匹配字段值。

相关推荐
liuyouzhang2 小时前
将基于Archery的web数据库审计查询平台封装为jdbc接口的可行性研究(基于AI)
前端·数据库
Meepo_haha5 小时前
配置 Redis
数据库·redis·缓存
u0109147607 小时前
CSS组件库如何快速扩展_通过Sass @extend继承基础布局
jvm·数据库·python
baidu_340998827 小时前
Golang怎么用go-noescape优化性能_Golang如何使用编译器指令控制逃逸分析行为【进阶】
jvm·数据库·python
m0_678485457 小时前
如何利用虚拟 DOM 实现无痕刷新?基于 VNode 对比的状态保持技巧
jvm·数据库·python
qq_342295827 小时前
CSS如何实现透明背景效果_通过RGBA色彩模式控制透明度
jvm·数据库·python
panzer_maus7 小时前
MySQL 索引介绍与索引优化的简单介绍
数据库·mysql
xiaotao1317 小时前
02-机器学习基础: 监督学习——线性回归
学习·机器学习·线性回归
Greyson17 小时前
CSS如何处理超长文本换行问题_结合word-wrap属性
jvm·数据库·python
captain3767 小时前
事务___
java·数据库·mysql