filters.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from __future__ import unicode_literals
  2. import itertools
  3. import django_filters
  4. from django import forms
  5. from django.utils.encoding import force_text
  6. #
  7. # Filters
  8. #
  9. class NumericInFilter(django_filters.BaseInFilter, django_filters.NumberFilter):
  10. """
  11. Filters for a set of numeric values. Example: id__in=100,200,300
  12. """
  13. pass
  14. class NullableCharFieldFilter(django_filters.CharFilter):
  15. null_value = 'NULL'
  16. def filter(self, qs, value):
  17. if value != self.null_value:
  18. return super(NullableCharFieldFilter, self).filter(qs, value)
  19. qs = self.get_method(qs)(**{'{}__isnull'.format(self.name): True})
  20. return qs.distinct() if self.distinct else qs
  21. class NullableModelMultipleChoiceField(forms.ModelMultipleChoiceField):
  22. """
  23. This field operates like a normal ModelMultipleChoiceField except that it allows for one additional choice which is
  24. used to represent a value of Null. This is accomplished by creating a new iterator which first yields the null
  25. choice before entering the queryset iterator, and by ignoring the null choice during cleaning. The effect is similar
  26. to defining a MultipleChoiceField with:
  27. choices = [(0, 'None')] + [(x.id, x) for x in Foo.objects.all()]
  28. However, the above approach forces immediate evaluation of the queryset, which can cause issues when calculating
  29. database migrations.
  30. """
  31. iterator = forms.models.ModelChoiceIterator
  32. def __init__(self, null_value=0, null_label='None', *args, **kwargs):
  33. self.null_value = null_value
  34. self.null_label = null_label
  35. super(NullableModelMultipleChoiceField, self).__init__(*args, **kwargs)
  36. def _get_choices(self):
  37. if hasattr(self, '_choices'):
  38. return self._choices
  39. # Prepend the null choice to the queryset iterator
  40. return itertools.chain(
  41. [(self.null_value, self.null_label)],
  42. self.iterator(self),
  43. )
  44. choices = property(_get_choices, forms.ChoiceField._set_choices)
  45. def clean(self, value):
  46. # Strip all instances of the null value before cleaning
  47. if value is not None:
  48. stripped_value = [x for x in value if x != force_text(self.null_value)]
  49. else:
  50. stripped_value = value
  51. super(NullableModelMultipleChoiceField, self).clean(stripped_value)
  52. return value