Python Django外键反向设置计数

Python Django外键反向设置计数,python,django,django-models,Python,Django,Django Models,因此,提供如下代码: class Category(models.Model): parent = models.ForeignKey('self', null=True, blank=True) name = models.CharField('name', max_length) category_three.category_set.count() == 0; # category_three has no children category_two.category_s

因此,提供如下代码:

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True)
    name = models.CharField('name', max_length)
category_three.category_set.count() == 0; # category_three has no children
category_two.category_set.count() != 0; # category_three's parent is category_two
我可能有这样一种关系:category_2的父对象是category_1,category_3的父对象是category 2

我想过滤掉所有没有孩子的类别。这意味着:

class Category(models.Model):
    parent = models.ForeignKey('self', null=True, blank=True)
    name = models.CharField('name', max_length)
category_three.category_set.count() == 0; # category_three has no children
category_two.category_set.count() != 0; # category_three's parent is category_two
但当我尝试这个:

Category.objects.filter(category_set__count=0) # this is the wrong code that won't work
# this would actually gives out the following error message
#Cannot resolve keyword 'category_set' into field. Choices are: category, id, name, parent, parent_id
基本上,我想要的是过滤掉所有的结束类别,这意味着不会有任何子类别


希望我解释清楚。你知道怎么做吗

尝试对批注进行筛选:

from django.db.models import Count

categories = Category.objects.annotate(num_children=Count('category_set')).filter(num_children__gt=0)
用“num\u children”字段(即“category\u set”字段的计数)注释每个类别,然后进行筛选,应该只会得到有子类别的类别。

使用“num\u isnull”查找:


在关系的上下文中,如果没有相关对象,_isnull=True匹配,如果至少有一个相关对象,_isnull=False匹配。或者,您可以将category\uuu isnull=True替换为category=None,这将生成相同的查询

无法将关键字“category_set”解析到字段中。选项包括:类别、id、名称、父项、父项_id@castiel该死,又弄错了。筛选器应为category\u isnull,而不是category\u set。我想我永远也学不到它,因为我总是用相关的名字…谢谢兄弟,这正是我想要的方式。