英文:
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 = {
'city': ['iexact', 'contains'],
'zipcode': ['exact', 'contains']
}
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='iexact')
...
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 = {
'city': ['iexact', 'contains'],
'zipcode': ['exact', 'contains']
}
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 = {
'city': ['iexact'],
'zipcode': ['exact', 'contains']
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论