python - Django 使用带有字典中多个值的 icontains 过滤器
问题描述
嗨,我正在尝试通过我得到的字典数据运行模型搜索查询:
{
"city":5,
"direction":"ne",
..other data that can be dynamic...
"address__icontains" = ["word1", "word2", "word3"],
}
我的搜索查询:
Models.objects.filter(**query_dict)
因为其他数据是动态的,所以我使用带有字典的过滤器。我使用__icontains来搜索包含该字符串中这 3 个单词的字段地址(字符串值),所以现在的问题是因为__icontains不接受查询集中这样的数组:
Models.objects.filter(other keys and values from dictionary, address__icontains= ["word1", "word2", "word3"])
我将如何使用字典过滤器搜索来完成这项工作?
我在 dict 中的数据有 3 种类型的字符串、int 和列表(1 用于范围搜索,另一种用于 icontains 搜索)我想将字典搜索与 icontains 和搜索结合起来
我也尝试将字典更改为
“地址__icontains”=“word1 word2 word3”
但它也不起作用
示例数据:
我正在做的是找到一个具有地址字段的属性,该地址字段具有城市、街道、病房和地区等动态数据
例如:
Đường ĐT 9(街), Xã Mỹ Hạnh Nam(区), Đức Hòa(区), Long An(市)
它还有其他数据,例如 direction="ne" 和在范围之间搜索的特殊数据,因此在字典中有像 "size__range": [0,1000] 这样的键
例如,如果 "address__icontains" = ["Long An", "Đức Hòa", "Xã Mỹ Hạnh Nam"] 那么它应该返回具有该地址的上述属性项,direction="ne" 并且 size 的值介于 0 和 1000 之间
感谢阅读
解决方案
这应该可以解决问题:
from operator import or_
from django.db.models import Q
from functools import reduce
instance = Model.objects.all()
def queryset_filter(instance, kwargs):
for key, value in kwargs.items():
if isinstance(value, list):
instance.filter(reduce(or_, (Q(key=x) for x in value))
else:
instance.filter(key=value)
return instance
您以这种方式进行了一些额外的迭代,但如果您的代码需要更复杂的过滤(例如使用表单中的查询集),那么无论如何您都需要以这种方式进行迭代。
推荐阅读
- css - 使用 css 制定屏幕尺寸规则或根据屏幕尺寸渲染组件?
- java - 图集上的 Heroku Spring boot + Mongo DB
- java - Groovy:如何模拟导入的类及其方法
- javascript - 为什么我在 css 中对我的背景图像做出反应时出错
- excel - 如何使用带有溢出的getElementsByTagName获取特定值:在VBA上隐藏?
- json - 正则表达式用 _ 替换引用字符串中的空格(崇高)
- node.js - 适用于 QnA Bot 的 Azure DevOps 管道
- python - Python Reaction Response 中的 Discord Bot
- python - 如果字典中存在部分查询,则添加 +1
- git - 我的 GitHub 操作只是挂在没有日志的启动状态,这是怎么回事?