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

相关推荐
是一个Bug38 分钟前
Agent(智能体)应用 的入门学习路径
学习·机器学习
●VON39 分钟前
鸿蒙Flutter实战:分类管理页BottomSheet CRUD
数据库·flutter·华为·harmonyos·鸿蒙
Cosolar40 分钟前
Chroma向量库面试学习指南
数据库·人工智能·面试·职场和发展·数据库架构
2301_809051141 小时前
Linux 网络编程 学习笔记
linux·网络·学习
eggcode2 小时前
【Qt学习】Linux(ARM架构)在线安装Qt6.x
linux·qt·学习·arm
企服AI产品测评局2 小时前
Agent适配信创环境实测:企业级自动化如何实现国产操作系统与数据库全兼容?
运维·数据库·人工智能·ai·chatgpt·自动化
cfm_29142 小时前
Redis数据安全性解析
数据库·redis·缓存
DIY源码阁2 小时前
JavaSwing学生成绩管理系统 - MySQL版
java·数据库·mysql·eclipse
_李小白3 小时前
【android opencv学习笔记】Day 26: 滤波算法之低通滤波与图像缩放插值
android·opencv·学习