2014-09-25 105 views
0

我有兩個型號。產品和類別。每個產品都有一個類別,而類別有一個slu。。現在,當你調用的URL '/catalog/adventure/',你應該看到與類別「冒險」所有產品的列表,當你寫「行動」,你應該能看到動作的產品等按類別篩選產品

所以我做了一個ListView

class BookListView(ListView): 
    template_name = 'project/shop/product-list-view.html' 

    def get_queryset(self): 
     category = get_object_or_404(Category, path=self.kwargs['slug']) 

     products = Product.objects.all().filter() 

     return products 

我必須在.filter()中寫什麼?

回答

0

這將有助於在這裏看到自己的模型,但假設產品有一個ForeignKey類別,它應該是這麼簡單:

products = Product.objects.all().filter(category=category) 
0

假設產品有一個ForeignKey類別,我寧願建議使用落後的關係與related_name:

class Product(models.Model): 
    ... 
    category = models.ForeignKey(Category, related_name='products') 
    ... 

,並在您的視圖:

products = category.products.all() 

無需過濾器。