20π
β
I use the same approach, but generic, using a mixin:
class FilterMixin(object):
def get_queryset_filters(self):
filters = {}
for item in self.allowed_filters:
if item in self.request.GET:
filters[self.allowed_filters[item]] = self.request.GET[item]
return filters
def get_queryset(self):
return super(FilterMixin, self).get_queryset()\
.filter(**self.get_queryset_filters())
class ImageListView(FilterMixin, ListView):
allowed_filters = {
'name': 'name',
'tag': 'tag__name',
}
# no need to override get_queryset
This allows to specify a list of accepted filters, and they donβt need to correspond to the actual .filter()
keywords. You can then expand it to support more complex filtering (split by comma when doing an __in
or __range
filter is an easy example)
π€rewritten
- Htaccess on heroku for django app
- Is it possible to make a mobile app in Django?
- Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it
Source:stackexchange.com