在django中组合过滤器

时间:2015-09-04 18:54:09

标签: python django filtering

我正在使用django_filters,我将它们相互组合有一点问题。

我有什么?基本过滤器,例如:

class BasicFilter(django_filters.FilterSet):
    class Meta:
        model = myModel
        fields = []


class TimeFilter(BasicFilter):
    created = django_filters.DateFromToRangeFilter(
        help_text='Date from - to', label='Time'
    )
    class Meta(BasicFilter.Meta):
        fields = ['created']


class AgentFilter(BasicFilter):
    agent = django_filters.ModelMultipleChoiceFilter(
        queryset=AgentClass.objects.all(), help_text=''
    )
    class Meta(BasicFilter.Meta):
        fields = ['agent']


class SomethingElseFilter(BasicFilter):
    something = django_filters.ModelMultipleChoiceFilter(
        queryset=SomethingElse.objects.all(), help_text=''
    )
    class Meta(BasicFilter.Meta):
        fields = ['something']

用户将决定他想要哪些过滤器,例如他将选择TimeFilter和AgentFilter,我需要将这个基本过滤器连接到一个ConnectedFilter。 然后我在我的观点中处理它,例如

class MyView(ListView):
model = myModel
template_name = "filters.html"

def get_queryset(self):
    qs=MyModel.objects.all()
    try:
        self.connected_filter = ConnectedFilter(
            self.request.GET, queryset = qs)

        return self.connected_filter
    except:
        return qs


def get_context_data(self, **kwargs):
    context = super(MyView, self).get_context_data(**kwargs)
    context['filter_form'] = self.connected_form.as_table()
    return context

或许还有一些更好的解决方案。

0 个答案:

没有答案