如何在django-filter扩展中传递带有exclude param的queryset

时间:2016-05-17 22:45:58

标签: python django django-queryset django-filter

我正在使用django-filterdjango-pure-pagination个扩展程序

class BuyFilterView(PaginationMixin, FilterView):
    filterset_class = ProductFilter
    template_name = "buy_filter.html"
    context_object_name = "goods"
    paginate_by = 50

    def get_context_data(self, **kwargs):
        context = super(BuyFilterView, self).get_context_data(**kwargs)
        context['cart'] = Cart.objects.get(user=self.request.user)
        return context


class ProductFilter(FilterSet):
    country = ChoiceFilter(choices=country_values)
    brand = ChoiceFilter(choices=brand_values)
    type = ChoiceFilter(choices=type_values)

    class Meta:
        model = Goods
        fields = {
            'country': ['exact'],
            'brand': ['exact'],
            'type': ['exact'],
        }

Goods模型中的某些项目具有空白价格值。我想从queryset中排除它们。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您可以稍微修改您的BuyFilterView和get_context_data()以显式调用ProductFilter并使用MultipleObjectMixin和TemplateView的组合:

class BuyFilterView(PaginationMixin, MultipleObjectMixin, TemplateView):
    template_name = "buy_filter.html"
    paginate_by = 50

    def get_context_data(self, **kwargs):
        context = super(BuyFilterView, self).get_context_data(**kwargs)
        context['cart'] = Cart.objects.get(user=self.request.user)
        context['goods'] = ProductFilter(request.GET,
                                         queryset=Goods.objects.exclude(price=''))
        return context

另一个,甚至更干净的选择是使用ListView并覆盖其get_queryset()方法:

class BuyFilterView(PaginationMixin, ListView):
    template_name = "buy_filter.html"
    paginate_by = 50

    def get_queryset(self):
        return ProductFilter(self.request.GET, queryset=Goods.objects.exclude(price=''))

    def get_context_data(self, **kwargs):
        context = super(BuyFilterView, self).get_context_data(**kwargs)
        context['cart'] = Cart.objects.get(user=self.request.user)
        return context