Django使用DRF进行任何字段的精确匹配筛选。

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

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_nonic_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=&#39;search_by_id&#39;, label=&#39;Search By ID&#39;)

    class Meta:
        model = Person
        fields = [&#39;id_no&#39;]

    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

huangapple
  • 本文由 发表于 2023年7月6日 15:30:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76626456.html
匿名

发表评论

匿名网友

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

确定