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

相关推荐
王道长服务器 | 亚马逊云9 分钟前
直播站怎么做到“低延迟不掉线”?AWS + 拳头链路的实战组合
服务器·数据库·搜索引擎·云计算·aws
BullSmall17 分钟前
《道德经》第六十七章
学习
e***09620 分钟前
【MySQL】MySQL库的操作
android·数据库·mysql
qy-ll22 分钟前
最新MMO-IG生成图像论文学习(25/11/19)
图像处理·深度学习·学习·计算机视觉·论文学习·遥感
wljt22 分钟前
Redis
数据库·redis·缓存
wljt27 分钟前
Redis常用命令
数据库·redis·oracle
Tiger_shl28 分钟前
SqlConnection、SqlCommand 和 SqlDataAdapter
开发语言·数据库·c#
fmk10231 小时前
TailwindCSS 学习笔记
笔记·学习
h***93661 小时前
【MySQL数据库】Ubuntu下的mysql
数据库·mysql·ubuntu
正在走向自律1 小时前
豆包编程模型Doubao-Seed-Code深度体验,从零开始构建全栈项目的完整指南
java·服务器·数据库·doubao·claude code·火山方舟