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

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

Django filter on DRF with exact match of any field

问题

我正在DRF上使用django filter,针对以下模型:

  1. class Customer(models.Model):
  2. passport_no = models.CharField(max_length=20, blank=True, null=True)
  3. nic_driving_license = models.CharField(max_length=20, blank=True, null=True)
  4. ...

我从前端发送passport_nonic_driving_license,格式为id_no=<value>。我该如何指定filterset_fields以在上述任一字段上进行精确匹配?以下方式不起作用,因为我认为它执行AND匹配。

  1. filterset_fields = {
  2. 'passport_no': ['exact'],
  3. 'nic_driving_license': ['exact']
  4. }
英文:

I'm using django filter on DRF with following model.

  1. class Customer(models.Model):
  2. passport_no = models.CharField(max_length=20, blank=True, null=True)
  3. nic_driving_license = models.CharField(max_length=20, blank=True, null=True)
  4. ...

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.

  1. filterset_fields = {
  2. 'passport_no': ['exact'],
  3. 'nic_driving_license': ['exact']
  4. }
  5. </details>
  6. # 答案1
  7. **得分**: 1
  8. 以下是翻译的内容:
  9. "在@wiaterb的建议下,我成功地做到了这一点。发布解决方案以帮助其他人。
  10. 注意:不需要指定`filterset_fields`。
  11. `views.py`
  12. ```python
  13. import django_filters
  14. from django.db.models import Q
  15. from .models import Person
  16. class IDFilter(django_filters.FilterSet):
  17. id_no = django_filters.CharFilter(method='search_by_id', label='按ID搜索')
  18. class Meta:
  19. model = Person
  20. fields = ['id_no']
  21. def search_by_id(self, queryset, name, value):
  22. return queryset.filter(
  23. Q(passport_no=value) | Q(nic_driving_license=value)
  24. )
  25. class PersonViewSet(viewsets.ModelViewSet):
  26. ...
  27. 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

  1. import django_filters
  2. from django.db.models import Q
  3. from .models import Person
  4. class IDFilter(django_filters.FilterSet):
  5. id_no = django_filters.CharFilter(method=&#39;search_by_id&#39;, label=&#39;Search By ID&#39;)
  6. class Meta:
  7. model = Person
  8. fields = [&#39;id_no&#39;]
  9. def search_by_id(self, queryset, name, value):
  10. return queryset.filter(
  11. Q(passport_no=value) | Q(nic_driving_license=value)
  12. )
  13. class PersonViewSet(viewsets.ModelViewSet):
  14. ...
  15. 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:

确定