如何在Django中为(基于类)的通用对象列表创建一个过滤器窗体? [英] How to create a filter form for a (class based) generic object list in Django?

查看:94
本文介绍了如何在Django中为(基于类)的通用对象列表创建一个过滤器窗体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Django 1.3的基于类的通用视图来显示图像列表,但是我想添加一个过滤器,使用户能够缩小显示的结果。

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 current approach works, but feels quite hackish:

class ImageFilterForm(ModelForm):
    class Meta:
        model = Image

class ImageListView(ListView):
    model = Image

    def get_queryset(self):
        qs = Image.objects.select_related()  
        for item in self.request.GET:
            key, value = item, self.request.GET.getlist(item)
            # ... Filtering here ...
        return qs

    def get_context_data(self, **kwargs):
        context = super(ImageListView, self).get_context_data(**kwargs)
        context['filter_form'] = ImageFilterForm(self.request.GET)
        return context

有没有更好的方法来添加自定义过滤到通用视图?

Are there better means to add custom filtering to a generic view?

推荐答案

我使用同样的方法,但通用,使用mixin:

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

这允许指定接受过滤器的列表,而不需要对应于实际的 .filter()关键字。然后,您可以扩展它以支持更复杂的过滤(在或 __范围中执行 __时以逗号分隔,过滤器是一个简单的例如)

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)

这篇关于如何在Django中为(基于类)的通用对象列表创建一个过滤器窗体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆