filters.py 3.4 KB

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