【问题标题】:Django using icontains filter with multiple values from dictionaryDjango使用icontains过滤器和字典中的多个值
【发布时间】:2020-02-01 11:23:36
【问题描述】:

您好,我正在尝试通过 dictionary 数据运行模型搜索查询,结果如下:

{
   "city":5,
   "direction":"ne",
   ..other data that can be dynamic...
   "address__icontains" = ["word1", "word2", "word3"],
}

我的搜索查询:

 Models.objects.filter(**query_dict)

因为其他数据是动态,所以我使用带有字典的过滤器。我使用 __icontains 来搜索字段 address( string value) 包含该字符串中的这 3 个单词,所以现在的问题是因为 __icontains 不接受 array 像这样在查询集中:

Models.objects.filter(other keys and values from dictionary, address__icontains= ["word1", "word2", "word3"])

我将如何使用字典过滤器搜索来完成这项工作?

我在 dict 中的数据有 3 种类型的字符串、int 和列表(1 用于范围搜索,另一种用于 icontains 搜索)我想将字典搜索与 icontains AND 搜索结合起来

我也试过把字典改成

"address__icontains" = "word1 word2 word3"

但它也不起作用

示例数据:

我正在做的是找到一个属性,该属性的地址字段包含城市、街道、病房和地区等动态数据

例如:

Đường ĐT 9(街道),Xã Mỹ Hạnh Nam(区),Đức Hòa(区),龙 一个(城市)

它还有其他数据,例如 direction="ne" 和 specials 在范围之间搜索的数据,因此在字典中有像 "size__range": [0,1000] 这样的键

例如,如果 "address__icontains" = ["Long An", "Đức Hòa", "Xã Mỹ Hạnh Nam"] 那么它应该返回带有该地址的上述 Property 项目,direction=" ne" 并且 size 的值在 0 到 1000 之间

感谢阅读

【问题讨论】:

  • 应该是address__icontains 而不是"address__icontains"
  • 是的,我打错了对不起,已修复
  • 这里是another example 如何做到这一点
  • 哦,好的,我没有及时看到编辑,它似乎有效,我将尝试一些查询并测试结果

标签: python django django-queryset django-filter


【解决方案1】:

这应该可以解决问题:

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

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

【讨论】:

  • 在字典中我也有 'road__range': [0, 1000] 我已经在过滤器中使用它进行范围搜索,所以它也是一个列表
  • 我使用示例数据对我的帖子进行了编辑,如果 isinstance(value, list): 无法应用,因为某些数据是范围,所以它是列表类型值
猜你喜欢
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 2021-12-08
  • 2013-02-09
  • 1970-01-01
  • 2021-01-23
  • 2018-12-09
  • 2022-06-22
相关资源
最近更新 更多