Django过滤器为项目列表生成过滤器

ac1kyiln  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(279)

我想根据逗号查询参数过滤字段vehicle_type

{{url}}/vehicles-records-info/75d9ee1b-8a03-4697-82e7-2d96ef0a8c2d/?vehicle_type=Mixer,Lorry

但是,当我打印查询时,生成的查询是

...  AND "vehicle_type" IN (M, i, x, e, r, ,, L, o, y))

但是查询应该是

...  AND "vehicle_type" IN ('Mixer', 'Lorry'))

下面是我的代码

过滤器

class VehicularAccessRecordInformationFilter(django_filters.FilterSet):
    vehicle_type = django_filters.CharFilter(field_name='vehicle_type', lookup_expr='in')
    start_timestamp = django_filters.DateTimeFilter(field_name='timestamp', lookup_expr='gte')
    end_timestamp = django_filters.DateTimeFilter(field_name='timestamp', lookup_expr='lte')

    class Meta:
        model = VehicleAccessRecordInformation
        fields = ['vehicle_type', 'timestamp']
    ```
eqqqjvef

eqqqjvef1#

这可能有助于:

from django_filters import rest_framework as filters

class CharInFilter(filters.BaseInFilter, filters.CharFilter):
    pass

class VehicularAccessRecordInformationFilter(filters.FilterSet):
    vehicle_type = CharInFilter(field_name='vehicle_type')
    ...

    class Meta:
        model = VehicleAccessRecordInformation
        fields = ['vehicle_type', <other_fields>]

BaseInFilter接受逗号分隔的多个值,并且CharFilter为这些值定义了一个类型,即您可以使用NumberFilterChoiceFilter等。
因此?vehicle_type=Mixer,Lorry的计算结果为

VehicleAccessRecordInformation.objects.filter(vehicle_type__in=['Mixer', 'Lorry']

相关问题