你可以用
product_set
作为在Django中默认创建的相关名称,或者您最好自己创建一个相关名称。一个
属于
类别
,但是
类别
可以有很多
产品
为此,请为
category
Product
:
category = models.ForeignKey(
Category,
on_delete=models.CASCADE,
related_name='products'
)
现在在你的
views.py
class CategoryDetailView(DetailView):
model = Category
# remove the line below
category_products = Category.product_set.all()
# don't prefix the fields like this, it's ugly and redundant
# call it just slug, not category_slug, adjust in urls.py
slug_url_kwarg = "category_slug"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# where did you get self.categories?
context['categories'] = self.categories
# and this won't work anymore too
context['category_products'] = self.category_products
return context
在
CategoryDetailView
只显示一个类别。这是一个详细的视图-它只包含一个对象。所以你不会用
. 对象在方法中可用。我们就是这样重写的:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
products = self.object.products.all()
context['products'] = products
return context