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

相关推荐
亚林瓜子19 小时前
AWS Glue Python Shell任务中读取Athena数据库
数据库·python·shell·aws·glue·athena
zhangchaoxies19 小时前
Golang怎么用K8s Secret管理密钥_Golang如何从K8s Secret安全读取密码和证书【操作】
jvm·数据库·python
2402_8548083719 小时前
JavaScript中模块化在游戏引擎开发中的资源调度作用
jvm·数据库·python
Hical_W19 小时前
深入学习CPP26_静态反射
c++·学习
SeaTunnel20 小时前
深度解析 Apache SeaTunnel 核心引擎三大技术创新:高可靠异步持久化与 CDC 架构优化实战
大数据·数据库·架构·apache·seatunnel
2401_8654396321 小时前
HTML函数在低温环境下启动慢吗_温度对硬件启动影响【方法】
jvm·数据库·python
NotFound48621 小时前
分享实战心得PostgreSQL 主从复制:告别单点故障,附主从切换与延迟监控命令
数据库·postgresql
夜瞬1 天前
NLP学习笔记01:文本预处理详解——从清洗、分词到词性标注
笔记·学习·自然语言处理
minebmw71 天前
Oracle 19.29 中 ORA-00600 [4193] 错误完全解析与恢复指南
数据库·oracle
m0_377618231 天前
Golang怎么连接MySQL数据库_Golang MySQL连接教程【总结】
jvm·数据库·python