使用django的objects.filter()方法匹配多个关键字的方法
作者:成为CTO 时间:2022-04-08 06:11:20
介绍:
今天在使用django的时候忽然想用到,如何匹配多个关键字的操作,我们知道django有一个objects.filter()方法,我们可以通过如下一句代码实现匹配数据库中title包含key关键词的文章名称。
table.objects.filter(title__contains=key)
问题:
但是我的需求是我不仅仅只需要匹配出一个关键字的文章而是多个关键字的文章,那么我们该如何使用django的objects.filter()?
table.objects.filter(title__contains=key1)+.objects.filter(title__contains=key2)+....?
解决:
我们都知道在正常的sql语句中如果我们需要匹配多个关键字的title可以这样做
select title from data where title regexp 'key1|key2'
select title from data where title like '%key1%' or like '%key2%'
以上的两种sql语句都是选择出title属性中存在key1和key2的所有文章,那么django是不是也会有一种方法匹配多个关键字呢?当然有就是下面的代码
from django.db.models import Q
table.object.filter(Q(title__startswith='key1') | Q(title__startswith='key2'))
首先导入django的Q方法然后在filter中添加对应的匹配即可
来源:https://blog.csdn.net/m0_43432638/article/details/89853351
标签:django,objects,filter,关键字
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何查询日期类型的数据?
2009-11-11 20:04:00
OpenCV 边缘检测
2023-08-19 22:54:20
![](https://img.aspxhome.com/file/2023/0/92120_0s.jpg)
Django contrib auth authenticate函数源码解析
2022-04-27 01:49:23
Bootstrap实现圆角、圆形头像和响应式图片
2023-08-12 07:16:59
![](https://img.aspxhome.com/file/2023/2/56052_0s.jpg)
numpy数据类型dtype转换实现
2021-08-09 09:36:37
MySQL 基本概念
2011-09-10 16:22:34
Python导入不同文件夹中文件的方法详解
2022-01-22 09:30:08
![](https://img.aspxhome.com/file/2023/7/66297_0s.png)
pandas loc与iloc用法及区别
2023-01-22 08:26:53
![](https://img.aspxhome.com/file/2023/7/84947_0s.png)
Django权限控制的使用
2023-12-27 01:50:57
![](https://img.aspxhome.com/file/2023/9/85269_0s.png)
SQL Server2000的安全策略
2007-08-06 17:14:00
基于python3.7利用Motor来异步读写Mongodb提高效率(推荐)
2022-12-20 08:44:05
![](https://img.aspxhome.com/file/2023/4/80474_0s.png)
python 使用pandas计算累积求和的方法
2021-05-22 19:46:16
Matplotlib 绘制饼图解决文字重叠的方法
2023-06-12 22:23:06
![](https://img.aspxhome.com/file/2023/4/60504_0s.png)
Python request中文乱码问题解决方案
2023-11-20 16:16:43
SQL Server如何实现快速删除重复记录?
2011-05-03 11:18:00
python基础之Numpy库中array用法总结
2022-05-10 11:59:53
JavaScript Dom编程:介绍学习书籍
2008-02-20 08:32:00
python读取Excel实例详解
2021-05-25 16:10:44
python opencv之SIFT算法示例
2023-12-27 21:42:33
![](https://img.aspxhome.com/file/2023/0/65950_0s.png)
go slice 数组和切片使用区别示例解析
2023-06-22 04:07:16
![](https://img.aspxhome.com/file/2023/0/87610_0s.jpg)