英文:
Django filters to generates filter for list of items
问题
我想基于逗号查询参数来过滤车辆类型字段
{{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'))
以下是我的代码
Filter
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']
```
<details>
<summary>英文:</summary>
I want to filter the field vehicle_type based on comma query params
{{url}}/vehicles-records-info/75d9ee1b-8a03-4697-82e7-2d96ef0a8c2d/?vehicle_type=Mixer,Lorry
However when I print the query the generated query is
... AND "vehicle_type" IN (M, i, x, e, r, ,, L, o, y))
But the query should be
... AND "vehicle_type" IN ('Mixer', 'Lorry'))
Here are my code
**Filter**
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']
```
答案1
得分: 1
这可能有所帮助:
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', '<其他字段>']
BaseInFilter
接受由逗号分隔的多个值,而 CharFilter
定义了值的类型,例如你可以使用 NumberFilter
、ChoiceFilter
等等。
因此,?vehicle_type=Mixer,Lorry
会被解释为:
VehicleAccessRecordInformation.objects.filter(vehicle_type__in=['Mixer', 'Lorry'])
英文:
This may help:
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
accepts multiple values separated by comma, and CharFilter
defines a type for the values, i.e. you can use NumberFilter
, ChoiceFilter
, etc.
So that ?vehicle_type=Mixer,Lorry
evaluates to
VehicleAccessRecordInformation.objects.filter(vehicle_type__in=['Mixer', 'Lorry']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论