Commits

Luke Plant committed 96bf880

Corrected use of FILTER_ONLY_CHOICE for ManyToMany and nullable ForeignKey fields

Comments (0)

Files changed (2)

django_easyfilters/filters.py

         params.pop('page', None) # links should reset paging
         return params
 
-    def normalize_add_choices(self, choices):
-        if len(choices) == 1:
-            # No point giving people a choice of one
-            choices = [FilterChoice(label=choices[0].label,
-                                    count=choices[0].count,
-                                    link_type=FILTER_ONLY_CHOICE,
-                                    params=None)]
-        return choices
+    def normalize_add_choices(self, choice):
+        raise NotImplementedError()
 
     def sort_choices(self, qs, params, choices):
         """
             count_dict[val] = count
         return count_dict
 
+    def normalize_add_choices(self, choices):
+        if len(choices) == 1 and not self.field_obj.null:
+            # No point giving people a choice of one, since all the results will
+            # already have the selected value (apart from nullable fields, which
+            # might have null)
+            choices = [FilterChoice(label=choices[0].label,
+                                    count=choices[0].count,
+                                    link_type=FILTER_ONLY_CHOICE,
+                                    params=None)]
+        return choices
+
     def get_choices(self, qs, params):
         choices_remove = self.get_choices_remove(qs, params)
         if len(choices_remove) > 0:
         choices_add = self.sort_choices(qs, params, choices_add)
         return choices_remove + choices_add
 
+    def normalize_add_choices(self, choices):
+        return choices
 
 class ManyToManyFilter(MultiValueFilterMixin, Filter):
     def __init__(self, *args, **kwargs):

django_easyfilters/tests/filterset.py

         self.assertFalse(qs_emily_anne.filter(name='Wuthering Heights').exists())
 
         # The choices should contain just emily and anne to remove, and
-        # charlotte should have 'link_type' set to FILTER_ONLY_CHOICE, and
-        # params set to None, because there is no point adding a filter when it
-        # is the only choice.
+        # charlotte should have 'link_type' FILTER_ADD. Even though it
+        # is the only choice, adding the choice is not necessarily the same as
+        # not adding it (could have books by Rmily and Anne, but not charlotte)
         choices = filter_.get_choices(qs_emily_anne, data)
         self.assertEqual([(c.label, c.link_type) for c in choices],
                          [(unicode(emily), FILTER_REMOVE),
                           (unicode(anne), FILTER_REMOVE),
-                          (unicode(charlotte), FILTER_ONLY_CHOICE)])
-        self.assertEqual(choices[2].params, None)
+                          (unicode(charlotte), FILTER_ADD)])
 
     def test_order_by_count(self):
         """