Django:如何查询自关联模型中无后代的顶级条目
Django自关联模型查询:无父级且无后代的条目
问题场景
现有自关联模型Critters,初始有3个无父级的条目,后续新增2个分别归属前两个条目的子项,需要查询无父级且无后代的条目(即示例中的第3个无父级条目),且不能通过name字段过滤。
修正后的模型(补全必填参数+优化反向关联)
首先注意原模型的CharField缺少必填的max_length参数,同时建议显式指定反向关联名称以便更直观查询:
from django.db import models class Critters(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey( 'self', blank=True, null=True, on_delete=models.CASCADE, related_name='children' # 显式指定反向关联名称,替代默认的`critters_set` )
查询实现代码
利用annotate统计每个条目的子项数量,再结合条件过滤:
from django.db.models import Count # 查询无父级且无后代的条目 target_critters = Critters.objects.annotate( child_count=Count('children') # 统计当前条目拥有的子项数量 ).filter( parent__isnull=True, # 筛选无父级的条目 child_count=0 # 筛选无后代(子项数量为0)的条目 )
代码说明
annotate(child_count=Count('children')):为每个Critters实例动态添加child_count字段,值为该实例关联的子项总数parent__isnull=True:过滤出自身没有父级的顶级条目child_count=0:过滤出没有任何子项(即无后代)的条目
两个条件叠加后,就能精准定位到符合要求的条目。
如果不想修改原模型(不添加related_name),则使用Django默认的反向关联名称critters_set即可:
target_critters = Critters.objects.annotate( child_count=Count('critters_set') ).filter( parent__isnull=True, child_count=0 )
内容的提问来源于stack exchange,提问作者swasher
相关产品推荐
相关产品推荐

