首页 > 解决方案 > 如何过滤所有子类别的查询集

问题描述

我有一个模型:

class Category(models.Model):
    title = models.CharField(max_length=127)
    # Lookups would be as follows:
    # cat = Category.objects.get(...)
    # for sub_cat in cat.sub_categories.all():
    parent = models.ForeignKey(
        "self",
        on_delete=models.CASCADE,
        related_name="sub_categories")

显然在模板中我可以过滤所有子类别:

{% for sub_cat in cat.sub_categories.all %}

我想将子类别的查询集传递给表单:

self.fields['parent'].queryset = PoliciesAndProceduresCategory.subcategories.all()

但这给出了错误:

AttributeError:类型对象“PoliciesAndProceduresCategory”没有属性“子类别”

有没有一种简单的方法来过滤这个,或者我必须做一些事情,比如定义一个Model Method

谢谢!

标签: django

解决方案


我发现了如何:

self.fields['parent'].queryset = Category.objects.filter(parent=None)

我试过的问题是:

self.fields['parent'].queryset = Category.objects.filter(parent=False)

我把我的 JS 和 Django 搞混了!


推荐阅读