django-filter 實現過濾時查詢是否包含在陣列的方法,in陣列的實現
阿新 • • 發佈:2021-11-30
from django_filters import BaseInFilter,NumberFilter class NumberInFilter(BaseInFilter, NumberFilter): pass class OrderFilter(django_filters.FilterSet): code = django_filters.CharFilter(field_name='code', lookup_expr='icontains') status = NumberInFilter(field_name='status',lookup_expr='in') type = NumberInFilter(field_name='type',lookup_expr='in') start_time = django_filters.DateTimeFilter(field_name='create_time',lookup_expr='gte',help_text = '%Y-%m-%d %H:%M:%S') end_time = django_filters.DateTimeFilter(field_name='create_time',lookup_expr='lt') name = django_filters.CharFilter(field_name='name',lookup_expr='icontains') pu_id= django_filters.NumberFilter(field_name='pu_id',lookup_expr='exact') l_id= django_filters.NumberFilter(field_name='l_id',lookup_expr='exact') l_name = django_filters.CharFilter(field_name='l_id',method='get_l_id') pt_name = django_filters.CharFilter(field_name='pu_id',method='get_pt_name') def get_pt_name(self,queryset,name,value): pu_id = list(User.objects.filter(pt_name__icontains=value).values_list('id',flat=True)) return queryset.filter(pu_id__in=pu_id) def get_l_id(self,queryset,name,value): l_id = list(Location.objects.filter(l_name__icontains=value).values_list('id',flat=True)) return queryset.filter(l_id__in=l_id) class Meta: model = Order fields = ['code','status','type','start_time','end_time','name','pu_id','l_id','l_name','pt_name']
https://django-filter.readthedocs.io/en/stable/ref/filters.html?highlight=BaseInFilter#baseinfilter