我编写了这个允许用户过滤和查询数据的Django视图集
from django_filters import rest_framework as filters
from rest_framework import viewsets
from API.models import Record
from API.serializers import RecordSerializer
class CountViewSet(viewsets.ReadOnlyModelViewSet):
"""List of all traffic count Counts"""
queryset = Record.objects.all().select_related("count")
serializer_class = RecordSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = (
"road",
"date",
"count_method",
"count_method__basic_count_method",
"count_method__detailed_count_method",
"location",
"road__direction",
"road__category",
"road__junc_start",
"road__junc_end",
"road__road__name",
"date__year",
"location__count_point_ref",
"road__category__name",
"road__junc_start__name",
"road__junc_end__name",
"road__direction__name",
)
我想使它不区分大小写,并允许搜索包含部分字符串,以便用户可以查询而不知道正确的"道路名称",例如:
curl -X GET/count/?road__category__name=TA"-H "accept: application/json
你可以尝试road__category__name__icontains
,如果它不工作,你必须声明它作为自定义过滤器类中的方法文件,i
字母,不区分大小写;文档参考:Django包含Doc.