【问题标题】:Why isn't the filter working?为什么过滤器不起作用?
【发布时间】:2017-06-14 10:52:31
【问题描述】:

我想按国家和品牌过滤我的产品,因此我创建了一个视图:

class CategoryView(ListView):
    template_name = '__index.html'
    context_object_name = 'products'
    paginate_by = 20

    def get_queryset(self):
        queryset = Product.objects.filter(category__slug=self.kwargs.get('slug')).order_by('-created')

        request = self.request

        # Filter By Brand and Country
        if request.GET.get('country'):
            print(request.GET.get('country'))
            queryset.filter(brand__country__slug=request.GET.get('country'))

        if request.GET.get('brand'):
            print(request.GET.get('brand'))
            queryset.filter(brand__slug=request.GET.get('brand'))

        print(queryset[0].brand.slug)
        print(queryset[0].brand.country.slug)

        return queryset

但是当我像这样传递查询字符串时,产品没有过滤:?brand=astra-gold&country=chehiya 并且打印功能显示给我:

切希亚 阿斯特拉金 威尼托 意大利

如您所见 chehiya != italiya 和 astra-gold != veneto。包子为什么会这样?

【问题讨论】:

    标签: django django-views django-queryset


    【解决方案1】:

    当您在查询集上调用 filter() 时,它会创建一个新的查询集。原始查询集没有改变。为了使您的过滤器生效,您需要将结果分配回queryset,例如:

        if request.GET.get('country'):
            print(request.GET.get('country'))
            queryset = queryset.filter(brand__country__slug=request.GET.get('country'))
    

    【讨论】:

      【解决方案2】:

      我忘了这个

      queryset = queryset.filter(brand__country__slug=request.GET.get('country'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2023-01-13
        • 2011-05-06
        • 2023-03-13
        • 1970-01-01
        相关资源
        最近更新 更多