首页 > 解决方案 > 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 之间

感谢阅读

标签: pythondjangodjango-querysetdjango-filter

解决方案


这应该可以解决问题:

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

您以这种方式进行了一些额外的迭代,但如果您的代码需要更复杂的过滤(例如使用表单中的查询集),那么无论如何您都需要以这种方式进行迭代。


推荐阅读