Skip to main content
 首页 » 编程设计

python之Django 外键反向设置计数

2025年05月04日30bhlsheji

因此,提供如下代码:

class Category(models.Model): 
    parent = models.ForeignKey('self', null=True, blank=True) 
    name = models.CharField('name', max_length) 

我可能有这样的关系:category_two 的父级是 category_one,category_three 的父级是 category two。

我想过滤掉所有没有 child 的类别。这意味着像这样:

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 

基本上我想要的是过滤掉所有结束类别,意味着不会有任何 child 的类别。

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

请您参考如下方法:

尝试过滤注释:

from django.db.models import Count 
 
categories = Category.objects.annotate(num_children=Count('category_set')).filter(num_children__gt=0) 

用“num_children”字段注释每个类别,这是“category_set”字段的计数,然后过滤应该只得到有子类别的类别。