How to pass queryset with exclude param in django

I'm using django-filter and django-pure-pagination extensions

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'],
        }

Some items in Goods model have blank price value. I want to exclude them from queryset. How can I do this?


You can slightly modify your BuyFilterView and get_context_data() to explicitly call ProductFilter and use combination of MultipleObjectMixin and 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

Another, maybe even more clean option is to use ListView and override its get_queryset() method:

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
链接地址: http://www.djcxy.com/p/38644.html

上一篇: Python中的管道字符

下一篇: 如何在django中使用排除参数传递queryset