【问题标题】:Django lookup_expr for arrayfield not matching exact string数组字段的 Django lookup_expr 与精确字符串不匹配
【发布时间】:2021-01-01 20:40:28
【问题描述】:

我有一个 djago 数组字段,

names = ArrayField(
    CICharField(max_length=255),
    blank=True,
    null=True,
    help_text="Additional names of the person.",
)

它有名字,

"names": [
        "Adam Bender",
        "April Watkins",
        "Daniel Brooks",
        "George Booker"
      ]

当我这样做时,

    names = django_filters.CharFilter(lookup_expr="icontains")

并搜索匹配记录的“Adam Bender”。 但是当我搜索“Adam Bend”时,它也是匹配的。 我不希望这样的事情发生。它应该与确切的名称匹配。 我试过iexact,但没用。

请指教。

【问题讨论】:

    标签: django


    【解决方案1】:

    您应该使用exact 而不是iexact

    exact 将返回完全匹配的结果。

    Entry.objects.get(id__exact=14)
    SELECT ... WHERE id = 14;
    

    iexact使用like运算符匹配结果。

    Blog.objects.get(name__iexact='beatles blog')
    SELECT ... WHERE name ILIKE 'beatles blog';
    

    【讨论】:

      【解决方案2】:

      我找到了解决办法。

      names = django_filters.CharFilter(method='names_filter')
      
      def names_filter(self, queryset, name, value):
          return queryset.filter(names__contains=[value])
      

      【讨论】:

        猜你喜欢
        • 2016-03-07
        • 2017-03-28
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        相关资源
        最近更新 更多