Kam*_*Dev 3 python django django-views
我想根据网址中的类别ID过滤子类别
对于恒定值,它可以正常工作
return Subcategory.objects.filter(category = 1)
Run Code Online (Sandbox Code Playgroud)
views.py
class SubcategoriesListView(ListView):
model = Subcategory
template_name = 'app/categories/index.html'
def get_queryset(self):
return Subcategory.objects.filter(category = category_id)
Run Code Online (Sandbox Code Playgroud)
urls.py
path('categories/<int:category_id>/', app.views.SubcategoriesListView.as_view(), name='subcategories'),
Run Code Online (Sandbox Code Playgroud)
models.py
class Subcategory(models.Model):
title = models.CharField(max_length=30)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
Run Code Online (Sandbox Code Playgroud)
追溯
/ categories / 1 /处的NameError未定义名称'category_id'
get_queryset中的views.py返回Subcategory.objects.filter(category = category_id)
您可以在基于类的视图中分别使用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'])Run Code Online (Sandbox Code Playgroud)
由于id是整数,因此您可以过滤category_id,而不是category。
| 归档时间: |
|
| 查看次数: |
1149 次 |
| 最近记录: |