get_queryset 中的 Django 2.0 url 参数 [英] Django 2.0 url parameters in get_queryset

查看:32
本文介绍了get_queryset 中的 Django 2.0 url 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据 URL 中的类别 id 过滤子类别

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)

追溯

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

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

推荐答案

您可以使用 self.args(元组)和 self.kwargs(一个字典)分别.

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.

这里你定义了category_id作为命名参数,所以你可以通过self.kwargs['category_id']获取它对应的值:

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'])

由于 id 是一个整数,因此您可以过滤 category_id,而不是 category.

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

这篇关于get_queryset 中的 Django 2.0 url 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆