filters.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from __future__ import unicode_literals
  2. import django_filters
  3. import itertools
  4. from django import forms
  5. from django.db.models import Q
  6. from django.utils.encoding import force_text
  7. #
  8. # Filters
  9. #
  10. class NumericInFilter(django_filters.BaseInFilter, django_filters.NumberFilter):
  11. """
  12. Filters for a set of numeric values. Example: id__in=100,200,300
  13. """
  14. pass
  15. class NullableModelMultipleChoiceField(forms.ModelMultipleChoiceField):
  16. """
  17. This field operates like a normal ModelMultipleChoiceField except that it allows for one additional choice which is
  18. used to represent a value of Null. This is accomplished by creating a new iterator which first yields the null
  19. choice before entering the queryset iterator, and by ignoring the null choice during cleaning. The effect is similar
  20. to defining a MultipleChoiceField with:
  21. choices = [(0, 'None')] + [(x.id, x) for x in Foo.objects.all()]
  22. However, the above approach forces immediate evaluation of the queryset, which can cause issues when calculating
  23. database migrations.
  24. """
  25. iterator = forms.models.ModelChoiceIterator
  26. def __init__(self, null_value=0, null_label='None', *args, **kwargs):
  27. self.null_value = null_value
  28. self.null_label = null_label
  29. super(NullableModelMultipleChoiceField, self).__init__(*args, **kwargs)
  30. def _get_choices(self):
  31. if hasattr(self, '_choices'):
  32. return self._choices
  33. # Prepend the null choice to the queryset iterator
  34. return itertools.chain(
  35. [(self.null_value, self.null_label)],
  36. self.iterator(self),
  37. )
  38. choices = property(_get_choices, forms.ChoiceField._set_choices)
  39. def clean(self, value):
  40. # Strip all instances of the null value before cleaning
  41. if value is not None:
  42. stripped_value = [x for x in value if x != force_text(self.null_value)]
  43. else:
  44. stripped_value = value
  45. super(NullableModelMultipleChoiceField, self).clean(stripped_value)
  46. return value
  47. class NullableModelMultipleChoiceFilter(django_filters.ModelMultipleChoiceFilter):
  48. """
  49. This class extends ModelMultipleChoiceFilter to accept an additional value which implies "is null". The default
  50. queryset filter argument is:
  51. .filter(fieldname=value)
  52. When filtering by the value representing "is null" ('0' by default) the argument is modified to:
  53. .filter(fieldname__isnull=True)
  54. """
  55. field_class = NullableModelMultipleChoiceField
  56. def __init__(self, *args, **kwargs):
  57. self.null_value = kwargs.get('null_value', 0)
  58. super(NullableModelMultipleChoiceFilter, self).__init__(*args, **kwargs)
  59. def filter(self, qs, value):
  60. value = value or () # Make sure we have an iterable
  61. if self.is_noop(qs, value):
  62. return qs
  63. # Even though not a noop, no point filtering if empty
  64. if not value:
  65. return qs
  66. q = Q()
  67. for v in set(value):
  68. # Filtering by "is null"
  69. if v == force_text(self.null_value):
  70. arg = {'{}__isnull'.format(self.name): True}
  71. # Filtering by a related field (e.g. slug)
  72. elif self.field.to_field_name is not None:
  73. arg = {'{}__{}'.format(self.name, self.field.to_field_name): v}
  74. # Filtering by primary key (default)
  75. else:
  76. arg = {self.name: v}
  77. if self.conjoined:
  78. qs = self.get_method(qs)(**arg)
  79. else:
  80. q |= Q(**arg)
  81. if self.distinct:
  82. return self.get_method(qs)(q).distinct()
  83. return self.get_method(qs)(q)