2017-06-14 71 views
0

我想按國家及品牌篩選我的產品,爲此,我已經創建了一個觀點:爲什麼過濾器不工作?

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 

但是當我通過查詢字符串這樣的產品是不是過濾:品牌= ASTRA-金&國家= chehiya和打印功能告訴我:

chehiya ASTRA-金 威尼託 italiya

正如你所看到的chehiya!= italiya和astra-gold!= veneto。 Bun爲什麼發生這種情況

回答

1

當您在查詢集調用filter(),它會創建一個新的查詢集。原始查詢集保持不變。爲了您的過濾器有效果,你需要將結果分配回queryset,例如:

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

這是恥辱)THX –

0

我忘了這

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