You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用django-filters按输入列表过滤字段(多国家代码场景)

实现支持国家代码列表过滤的FilterSet

完全可以用Django FilterSet实现这个需求,核心就是利用__in查询,下面是具体实现步骤:

1. 定义FilterSet类

假设你的模型是CountryRelatedModel,包含country_code字符字段(如果是外键关联的国家表,调整字段名即可):

import django_filters
from .models import CountryRelatedModel

class CountryRelatedFilter(django_filters.FilterSet):
    # 指定country_code字段使用in查询
    country_code = django_filters.CharFilter(lookup_expr='in')

    class Meta:
        model = CountryRelatedModel
        fields = ['country_code']

如果你的国家代码是通过外键关联的(比如关联Country模型,该模型有code字段),只需要修改字段名:

country_code = django_filters.CharFilter(field_name='country__code', lookup_expr='in')

2. 前端传参方式

FilterSet支持两种传参格式来传递代码列表:

  • 逗号分隔字符串:?country_code=US,CA
  • 重复参数:?country_code=US&country_code=CA

两种方式都会被自动解析为列表,匹配country_code属于列表中任一值的对象。

3. 在视图中使用FilterSet

以DRF的视图集为例,配置FilterSet即可生效:

from rest_framework import viewsets
from .models import CountryRelatedModel
from .filters import CountryRelatedFilter
from .serializers import CountryRelatedSerializer

class CountryRelatedViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = CountryRelatedModel.objects.all()
    serializer_class = CountryRelatedSerializer
    filterset_class = CountryRelatedFilter

前置要求

确保你已经安装并配置了django-filter:

  • 安装:pip install django-filter
  • 在settings.py的INSTALLED_APPS中添加'django_filters'
  • 如果用DRF,在REST_FRAMEWORK配置里添加:
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
    ]
    

内容的提问来源于stack exchange,提问作者Dash Winterson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:45:39