英文:
Django filter on DRF with exact match of any field
问题
我正在DRF上使用django filter,针对以下模型:
class Customer(models.Model):
    passport_no = models.CharField(max_length=20, blank=True, null=True)
    nic_driving_license = models.CharField(max_length=20, blank=True, null=True)
    ...
我从前端发送passport_no或nic_driving_license,格式为id_no=<value>。我该如何指定filterset_fields以在上述任一字段上进行精确匹配?以下方式不起作用,因为我认为它执行AND匹配。
filterset_fields = {
    'passport_no': ['exact'],
    'nic_driving_license': ['exact']
}
英文:
I'm using django filter on DRF with following model.
class Customer(models.Model):
    passport_no = models.CharField(max_length=20, blank=True, null=True)
    nic_driving_license = models.CharField(max_length=20, blank=True, null=True)
    ...
I'm sending either passport_no or nic_driving_license from the FE as id_no=<value>. How can I specify the filterset_fields to look for exact match on either of above fields? Following is not working since I think it does an AND match.
filterset_fields = {
    'passport_no': ['exact'],
    'nic_driving_license': ['exact']
}
</details>
# 答案1
**得分**: 1
以下是翻译的内容:
"在@wiaterb的建议下,我成功地做到了这一点。发布解决方案以帮助其他人。
注意:不需要指定`filterset_fields`。
`views.py`
```python
import django_filters
from django.db.models import Q
from .models import Person
class IDFilter(django_filters.FilterSet):
    id_no = django_filters.CharFilter(method='search_by_id', label='按ID搜索')
    class Meta:
        model = Person
        fields = ['id_no']
    def search_by_id(self, queryset, name, value):
        return queryset.filter(
            Q(passport_no=value) | Q(nic_driving_license=value)
        )
class PersonViewSet(viewsets.ModelViewSet):
    ...
    filterset_class = IDFilter
"
英文:
With the suggestion of @wiaterb I was able to do this exactly. Posting the solution to help others.
Note: No need to specify filterset_fields.
views.py
import django_filters
from django.db.models import Q
from .models import Person
class IDFilter(django_filters.FilterSet):
    id_no = django_filters.CharFilter(method='search_by_id', label='Search By ID')
    class Meta:
        model = Person
        fields = ['id_no']
    def search_by_id(self, queryset, name, value):
        return queryset.filter(
            Q(passport_no=value) | Q(nic_driving_license=value)
        )
class PersonViewSet(viewsets.ModelViewSet):
    ...
    filterset_class = IDFilter
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论