class DashboardSensorDataFilter(filters.FilterSet): station = filters.ModelChoiceFilter( label="Station", name="sensor__station_id", queryset=Station.objects.filter(current_status='ACTIVE'), widget=forms.Select) start_date = filters.IsoDateTimeFilter( label="Start Date", name="sensor_data_dateTime", lookup_expr='gte', widget=forms.DateTimeInput(attrs={'type': 'datetime-local'})) end_date = filters.IsoDateTimeFilter( label="End Date", name="sensor_data_dateTime", lookup_expr='lte', widget=forms.DateTimeInput(attrs={'type': 'datetime-local'})) sensor_type = filters.ModelChoiceFilter(label="Sensor Type *", name="sensor__sensor_type_id", queryset=SensorType.objects.all(), widget=forms.Select, required=True) order_by_field = 'ordering' ordering = OrderingFilter( # fields(('model field name', 'parameter name'),) fields=(('sensor_data_dateTime', 'sensor_data_dateTime'))) class Meta: model = SensorData fields = ['start_date', 'end_date', 'station', 'sensor_type']
class PropertyOrderingFilterSet(PropertyFilterSet): first_last_name = OrderingFilter( label='first_last_name', fields=( ('first_name', 'first_name'), ('last_name', 'Last Name'), ('username', 'username'), ('age', 'age') ), field_labels={ 'first_name': 'First Name', } ) property_first_last_name = PropertyOrderingFilter( label='property_first_last_name', fields=( ('prop_first_name', 'prop_first_name'), ('prop_last_name', 'Last Name'), ('prop_username', 'username'), ('prop_age', 'age') ), field_labels={ 'prop_first_name': 'First Name', } ) class Meta: model = models.OrderingFilterModel exclude = ['first_name', 'last_name', 'username', 'age']
class AdminCategoryFilter(FilterSet): o = OrderingFilter(fields=( ('name', 'name'), ('slug', 'slug'), )) class Meta: model = Category fields = []
def test_translation_default_label(self): with translation.override('pl'): f = OrderingFilter(fields=['username']) self.assertEqual(f.field.choices, [ ('', '---------'), ('username', 'Nazwa użytkownika'), ('-username', 'Nazwa użytkownika (malejąco)'), ])
class AdminProductFilter(FilterSet): o = OrderingFilter(fields=( ('name', 'name'), ('slug', 'slug'), )) class Meta: model = Product fields = []
def test_choices_from_fields(self): f = OrderingFilter(fields=(('a', 'c'), ('b', 'd')), ) self.assertSequenceEqual(f.field.choices, ( ('c', 'C'), ('-c', 'C (descending)'), ('d', 'D'), ('-d', 'D (descending)'), ))
class AdminCategoryDesignFilter(FilterSet): o = OrderingFilter(fields=( ('parent', 'parent'), ('name', 'name'), ('slug', 'slug'), )) class Meta: model = CategoryDesign fields = []
class AdminPrintTypeFilter(FilterSet): o = OrderingFilter(fields=( ('name', 'name'), ('slug', 'slug'), ('price', 'price'), )) class Meta: model = PrintType fields = []
def test_choices_unaltered(self): # provided 'choices' should not be altered when 'fields' is present f = OrderingFilter( choices=(('a', 'A'), ('b', 'B')), fields=(('a', 'c'), ('b', 'd')), ) self.assertSequenceEqual(f.field.choices, ( ('a', 'A'), ('b', 'B'), ))
class AdminColorFilter(FilterSet): o = OrderingFilter( fields=( ('name', 'name'), ('slug', 'slug'), ) ) class Meta: model = Color fields = []
class UserFilter(filters.FilterSet): username = filters.CharFilter(field_name='username', lookup_expr='icontains_accinsensitive') order_by_field = 'username' ordering = OrderingFilter(fields=(('username', 'username'), )) class Meta: model = User fields = ('username', )
class AdminDesignFilter(FilterSet): o = OrderingFilter( fields=( ('name', 'name'), ('slug', 'slug'), ('is_custom', 'is_custom'), ) ) class Meta: model = Design fields = []
def test_translation_override_label(self): with translation.override('pl'): f = OrderingFilter( fields=['username'], field_labels={'username': '******'}, ) self.assertEqual(f.field.choices, [ ('', '---------'), ('username', 'BLABLA'), ('-username', 'BLABLA (malejąco)'), ])
def test_field_labels(self): f = OrderingFilter( fields=(('a', 'c'), ('b', 'd')), field_labels={'a': 'foo'}, ) self.assertSequenceEqual(f.field.choices, ( ('c', 'foo'), ('-c', 'foo (descending)'), ('d', 'D'), ('-d', 'D (descending)'), ))
def test_field_labels_descending(self): f = OrderingFilter(fields=['username'], field_labels={ 'username': '******', '-username': '******', }) self.assertEqual(f.field.choices, [ ('', '---------'), ('username', 'BLABLA'), ('-username', 'XYZXYZ'), ])
class AdminLocationFilter(FilterSet): o = OrderingFilter(fields=( ('region', 'region'), ('city', 'city'), ('commune', 'commune'), ('address', 'address'), ('number', 'number'), ('alias', 'alias'), )) class Meta: model = Location fields = []
class MultiFilterTestFilterSet(PropertyFilterSet): number_order = OrderingFilter(fields=('number', 'number')) prop_number_order = PropertyOrderingFilter(fields=('prop_number', 'prop_number')) class Meta: model = models.MultiFilterTestModel fields = ['number', 'text', 'is_true', 'date', 'date_time'] property_fields = [ ('prop_number', PropertyNumberFilter, ['exact',]), ('prop_text', PropertyCharFilter, ['exact']), ('prop_is_true', PropertyBooleanFilter, ['exact']), ('prop_date', PropertyDateFilter, ['exact']), ('prop_date_time', PropertyDateTimeFilter, ['exact']), ]
class AllUserFilter(filters.FilterSet): q = django_filters.CharFilter(method='my_custom_filter') order_by_field = 'ordering' ordering = OrderingFilter(fields=(('id', 'position'), )) class Meta: model = User fields = ['q'] def my_custom_filter(self, queryset, name, value): return User.objects.filter( Q(firstName__icontains=value) | Q(middleName__icontains=value) | Q(lastName__icontains=value) | Q(company_name__icontains=value) | Q(phone_no__icontains=value) | Q(tin_no__icontains=value))
class TermFilter(FilterSet): order_by = OrderingFilter( fields = ( ('id', 'id'), ('wylie', 'wylie'), ('sa2ru1', 'sa2ru1'), ('sa2en1', 'sa2en1'), ('sa2ru2', 'sa2ru2'), ('sa2en2', 'sa2en2'), ('sa2ru3', 'sa2ru3'), ('sa2en3', 'sa2en3'), ('tibetan', 'tibetan'), ('sanscrit', 'sanscrit'), ) ) search = CharFilter('search', method='search_filter') def search_filter(self, queryset:QuerySet, name, value): if value == "": return queryset.none() # qval = Q(wylie__istartswith=value) | Q(sa2ru1__istartswith=value) | Q(sa2en1__istartswith=value) | Q(sa2ru2__istartswith=value) | Q(sa2en2__istartswith=value) | Q(sa2ru3__istartswith=value) | Q(sa2en3__istartswith=value) | Q(tibetan__istartswith=value) | Q(sanscrit__istartswith=value) qval = Q(wylie__iexact=value) | Q(sa2ru1__iexact=value) | Q(sa2en1__iexact=value) | Q(sa2ru2__iexact=value) | Q(sa2en2__iexact=value) | Q(sa2ru3__iexact=value) | Q(sa2en3__iexact=value) | Q(tibetan__iexact=value) | Q(sanscrit__iexact=value) return queryset.filter(qval) class Meta: model = Term fields = { "wylie": ["icontains"], "sa2ru1": ["icontains"], "sa2en1": ["icontains"], "sa2ru2": ["icontains"], "sa2en2": ["icontains"], "sa2ru3": ["icontains"], "sa2en3": ["icontains"], "tibetan": ["icontains"], "sanscrit": ["icontains"], }
class MeaningFilter(FilterSet): order_by = OrderingFilter( fields = ( ('id', 'id'), ('meaning', 'meaning'), ) ) search = CharFilter('search', method='search_filter') def search_filter(self, queryset:QuerySet, name, value): if value == "": return queryset.none() # qval = Q(meaning__icontains=value) # qval = Q(meaning__istartswith=value) qval = Q(meaning__iexact=value) return queryset.filter(qval) class Meta: model = Meaning fields = { "meaning": ["iexact"], # "meaning": ["icontains"], }
class SiaeOrderingFilter(FilterSet): # Mapping of the model property names -> query parameter names used to order the results: # - keys: the name of the property in the model in order to order the results # - values: the name of the ordering criterion in the query parameter # If you want to query https://some_api?o=cree_le, it will perform queryset.order_by("created_at") o = OrderingFilter(fields=SIAE_ORDERING_FILTER_MAPPING)
class AdminImageFilter(FilterSet): o = OrderingFilter(fields=(('path', 'path'), )) class Meta: model = Image fields = []
def test_help_text(self): # regression test for #756 - the ususal CSV help_text is not relevant to ordering filters. self.assertEqual(OrderingFilter().field.help_text, '') self.assertEqual(OrderingFilter(help_text='a').field.help_text, 'a')
def test_widget(self): f = OrderingFilter() widget = f.field.widget self.assertIsInstance(widget, widgets.BaseCSVWidget) self.assertIsInstance(widget, forms.Select)
def test_filtering_skipped_with_none_value(self): qs = mock.Mock(spec=['order_by']) f = OrderingFilter() result = f.filter(qs, None) self.assertEqual(qs, result)
class AdminSizeFilter(FilterSet): o = OrderingFilter(fields=(('name', 'name'), )) class Meta: model = Size fields = []
def test_filtering_with_fields(self): qs = mock.Mock(spec=['order_by']) f = OrderingFilter(fields={'a': 'b'}) f.filter(qs, ['b', '-b']) qs.order_by.assert_called_once_with('a', '-a')
class IzsekFilter(FilterSet): naslov = CharFilter(name='posnetek', lookup_expr='naslov__icontains', label="Naslov", help_text="") vsebina = CharFilter(name='vsebina', lookup_expr='icontains', label="Vsebina", help_text="") datum = DateFromToRangeFilter(name='posnetek__datum', widget=RangePickerWidget(), label="Datum", help_text="") oddaja = CharFilter(name='posnetek__oddaja', widget=ListSelect2(url='oddaja-url'), label="Oddaja", help_text="") tip_oddaje = CharFilter(lookup_expr='posnetek__oddaja__tip', widget=ListSelect2(url='tip-url'), label="Tip oddaje", help_text="") program = CharFilter(lookup_expr='posnetek__oddaja__program', widget=ListSelect2(url='program-url'), label="S programa", help_text="") o = OrderingFilter(fields=( ('posnetek__datum', 'datum'), ('posnetek__dolzina', 'dolzina'), ), field_labels={ 'datum': 'Datum', 'dolzina': 'Dolzina', }) class Meta: model = Izsek fields = {} order_by_field = '-posnetek__datum' def __init__(self, *args, **kwargs): super(IzsekFilter, self).__init__(*args, **kwargs) #ugh if self.data == {}: self.queryset = Posnetek.objects.all().order_by("-datum") @property def qs(self): qs = super(IzsekFilter, self).qs if hasattr(self.form, 'cleaned_data'): value = self.form.cleaned_data.get('vsebina', None) #dovolj dobro bo if value: qs = qs.extra( select={ 'snippet': "ts_headline('simple', \"vsebina\", plainto_tsquery(%s), 'StartSel=<span> , StopSel= </span>,MaxFragments=0,HighlightAll=TRUE')" }, select_params=[value, "style='background:lightblue;'"], ) return qs
def test_default_field(self): f = OrderingFilter() field = f.field self.assertIsInstance(field, forms.ChoiceField)
def test_filtering_descending(self): qs = mock.Mock(spec=['order_by']) f = OrderingFilter() f.filter(qs, ['-a']) qs.order_by.assert_called_once_with('-a')