How to create a filter form for a (class based) generic object list in Django?

后端 未结 2 353
有刺的猬
有刺的猬 2021-02-05 17:54

I\'m using Django 1.3\'s class based generic view to display a list of images, but I want to add a filter that enables the user to narrow down the displayed results.

My

相关标签:
2条回答
  • 2021-02-05 18:05

    Take a look at django-filter it easy solution for filtering data in view

    0 讨论(0)
  • 2021-02-05 18:29

    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)

    0 讨论(0)
提交回复
热议问题