Commits

Luke Plant committed 62aeaef

Added 'max_depth' parameter to DateTimeFilter

Comments (0)

Files changed (2)

django_easyfilters/filters.py

 
 class DateTimeFilter(ChooseAgainMixin, SingleValueMixin, DrillDownMixin, Filter):
 
+    max_depth_levels = {'year': YEAR.level,
+                        'month': MONTH.level,
+                        None: DAY.level + 1}
+
     def __init__(self, *args, **kwargs):
         self.max_links = kwargs.pop('max_links', 12)
+        self.max_depth = kwargs.pop('max_depth', None)
+        assert self.max_depth in ['year', 'month', None]
+        self.max_depth_level = self.max_depth_levels[self.max_depth]
         super(DateTimeFilter, self).__init__(*args, **kwargs)
 
     def choice_from_param(self, param):
         for date_choice, count in date_choice_counts:
             if date_choice in chosen:
                 continue
+
+            # To ensure we get the bridge choices, which are useful, we check
+            # self.max_depth_level late on and bailout here.
+            if range_type.level > self.max_depth_level:
+                continue
+
             choices.append(FilterChoice(date_choice.display(),
                                         count,
                                         self.build_params(add=date_choice),

django_easyfilters/tests/filterset.py

 
         self.assertEqual(choices[1].link_type, FILTER_DISPLAY)
 
+    def test_datetime_filter_max_depth(self):
+        qs = Book.objects.all()
+        params = MultiValueDict({'date_published':['1813']})
+        f = DateTimeFilter('date_published', Book, params, max_depth='year')
+        choices = f.get_choices(f.apply_filter(qs))
+        self.assertEqual(len(choices), 1)
+        self.assertEqual(choices[0].link_type, FILTER_REMOVE)
 
     def test_datetime_filter_invalid_query(self):
         self.do_invalid_query_param_test(lambda params: DateTimeFilter('date_published', Book, params, max_links=10),