|
| 1 | +from django.db.models import Q |
1 | 2 | from django.shortcuts import render
|
2 | 3 | from django_filters import widgets, fields, filters, NumberFilter, CharFilter
|
3 | 4 |
|
|
7 | 8 | from rest_framework.views import APIView
|
8 | 9 |
|
9 | 10 | from rest_framework_datatables import pagination as dt_pagination
|
| 11 | +from rest_framework_datatables.django_filters.filters import GlobalFilter |
10 | 12 | from rest_framework_datatables.django_filters.filterset import DatatablesFilterSet
|
11 | 13 | from rest_framework_datatables.django_filters.backends import DatatablesFilterBackend
|
12 | 14 |
|
@@ -77,23 +79,41 @@ class YADCFModelMultipleChoiceField(fields.ModelMultipleChoiceField):
|
77 | 79 | class YADCFModelMultipleChoiceFilter(filters.ModelMultipleChoiceFilter):
|
78 | 80 | field_class = YADCFModelMultipleChoiceField
|
79 | 81 |
|
| 82 | + def global_q(self): |
| 83 | + """ |
| 84 | + This method is necessary for the global filter |
| 85 | + - i.e. any string values entered into the search box. |
| 86 | + """ |
| 87 | + if not self._global_search_value: |
| 88 | + return Q() |
| 89 | + kw = "{}__{}".format(self.field_name, self.lookup_expr) |
| 90 | + return Q(**{kw: self._global_search_value}) |
| 91 | + |
| 92 | + |
| 93 | +class GlobalCharFilter(GlobalFilter, filters.CharFilter): |
| 94 | + pass |
| 95 | + |
| 96 | + |
| 97 | +class GlobalNumberFilter(GlobalFilter, filters.NumberFilter): |
| 98 | + pass |
| 99 | + |
80 | 100 |
|
81 | 101 | class AlbumFilter(DatatablesFilterSet):
|
82 | 102 |
|
83 |
| - # the name of this attribute must match the declared 'name' attribute in |
| 103 | + # the name of this attribute must match the declared 'data' attribute in |
84 | 104 | # the DataTables column
|
85 | 105 | artist_name = YADCFModelMultipleChoiceFilter(
|
86 |
| - field_name="artist", queryset=Artist.objects.all() |
| 106 | + field_name="artist__name", queryset=Artist.objects.all(), lookup_expr="contains" |
87 | 107 | )
|
88 | 108 |
|
89 | 109 | # additional attributes need to be declared so that sorting works
|
90 | 110 | # the field names must match those declared in the DataTables columns.
|
91 |
| - rank = NumberFilter() |
92 |
| - name = CharFilter() |
| 111 | + rank = GlobalNumberFilter() |
| 112 | + name = GlobalCharFilter() |
93 | 113 |
|
94 | 114 | class Meta:
|
95 | 115 | model = Album
|
96 |
| - fields = ("artist",) |
| 116 | + fields = ("artist_name", ) |
97 | 117 |
|
98 | 118 |
|
99 | 119 | class AlbumFilterListView(generics.ListAPIView):
|
|
0 commit comments