作者:奶油泡芙2覀21 | 来源:互联网 | 2022-12-08 12:07
我想根据网址中的类别ID过滤子类别
对于恒定值,它可以正常工作
return Subcategory.objects.filter(category = 1)
views.py
class SubcategoriesListView(ListView):
model = Subcategory
template_name = 'app/categories/index.html'
def get_queryset(self):
return Subcategory.objects.filter(category = category_id)
urls.py
path('categories//', app.views.SubcategoriesListView.as_view(), name='subcategories'),
models.py
class Subcategory(models.Model):
title = models.CharField(max_length=30)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
追溯
/ categories / 1 /处的NameError未定义名称'category_id'
get_queryset中的views.py返回Subcategory.objects.filter(category = category_id)
1> Willem Van O..:
您可以在基于类的视图中分别使用self.args
(元组)和self.kwargs
(字典)获得URI位置和命名参数。
在这里,您将定义category_id
为一个命名参数,因此可以通过以下方式获取其对应的值self.kwargs['category_id']
:
class SubcategoriesListView(ListView):
model = Subcategory
template_name = 'app/categories/index.html'
def get_queryset(self):
return Subcategory.objects.filter(category_id=self.kwargs['category_id'])
由于id
是整数,因此您可以过滤category_id
,而不是category
。