如何在django中使用排除参数传递queryset
我正在使用django-filter和django-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
模型中的某些项目具有空白价格值。 我想从查询集中排除它们。 我怎样才能做到这一点?
您可以稍微修改您的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
链接地址: http://www.djcxy.com/p/38643.html