iexact 在 django-filter 中声明可过滤字段时无效。

huangapple go评论50阅读模式
英文:

iexact doesn't work in declaring filterable field in django-filter

问题

我正在使用DRF的django-filter库

```python
class OrganizationFilter(FilterSet):

    class Meta:
        model = Organization
        fields = {
            'city': ['iexact', 'contains'],
            'zipcode': ['exact', 'contains']
        }

city: CharField

我想对城市字段进行不区分大小写的过滤。

我可以通过指定以下方式使其工作。

class OrganizationFilter(FilterSet):
    city = filters.CharFilter(lookup_expr='iexact')
    ...

除非我指定lookup_expr,否则它不起作用。

我想知道为什么?


<details>
<summary>英文:</summary>

I am using django-filter lib with DRF.

```python
class OrganizationFilter(FilterSet):

    class Meta:
        model = Organization
        fields = {
            &#39;city&#39;: [&#39;iexact&#39;, &#39;contains&#39;],
            &#39;zipcode&#39;: [&#39;exact&#39;, &#39;contains&#39;]
        }

city: CharField

I want to filter city field case-insensitive.

I can make it work by specifying the following.

class OrganizationFilter(FilterSet):
    city = filters.CharFilter(lookup_expr=&#39;iexact&#39;)
    ...

Unless If I don't specify the lookup_expr it's not working.

I want to know why?

答案1

得分: 0

原因是,代码无法运行的原因是:

fields = {
    'city': ['iexact'],
    'zipcode': ['exact', 'contains']
}

是因为你在 'iexact' 旁边指定了 'contains'Contains 将执行区分大小写的查找,这将与你的 iexact 查找冲突。所以你的代码应该是这样的:

class OrganizationFilter(FilterSet):
    class Meta:
        model = Organization
        fields = {
            'city': ['iexact'],
            'zipcode': ['exact', 'contains']
        }
英文:

The reason why, is not working:

fields = {
            &#39;city&#39;: [&#39;iexact&#39;, &#39;contains&#39;],
            &#39;zipcode&#39;: [&#39;exact&#39;, &#39;contains&#39;]
        }

Is because you specified 'contains' next to 'iexact'. Contains will perform a case-sensitive lookup which will be in conflict with you're iexact lookup. So you're code should look like:

class OrganizationFilter(FilterSet):
    class Meta:
        model = Organization
        fields = {
            &#39;city&#39;: [&#39;iexact&#39;],
            &#39;zipcode&#39;: [&#39;exact&#39;, &#39;contains&#39;]
        }

huangapple
  • 本文由 发表于 2023年2月19日 16:46:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定