Django 2.0 url parameters in get_queryset

瘦欲@ 提交于 2020-03-19 05:11:36

问题


I would like to filter subcategories based on the category id from the url

For a constant value it works without a problem

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/<int:category_id>/', 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)

Traceback

NameError at /categories/1/ name 'category_id' is not defined

views.py in get_queryset return Subcategory.objects.filter(category = category_id)


回答1:


You can obtain the URI positional and named parameters in a class-based view with self.args (a tuple) and self.kwargs (a dictionary) respectively.

Here you defined the category_id as a named parameter, so you can obtain its corresponding value with 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'])

Since the id is an integer, you thus filter on category_id, not on category.



来源:https://stackoverflow.com/questions/51755692/django-2-0-url-parameters-in-get-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!