如何计算查询集中的子对象? 我有模特:
class SomeTree(Model):
parent = ForeignKey('self', on_delete=SET_NULL)
level = IntegerField(default=0)
qs = SomeTree.objects.filter(level=0).annotate(childes_count=???)
我需要将直接子对象计算为对象。在Django ORM中可以吗?
答案 0 :(得分:0)
非常简单,您可以使用count()
方法来计算记录数。
qs = SomeTree.objects.filter(level=0).count() # returns number of filtered records.
答案 1 :(得分:0)
可以这样做:
class SomeTree(Model):
parent = ForeignKey('self', on_delete=SET_NULL, related_name='childes')
level = IntegerField(default=0)
qs = SomeTree.objects.filter(level=0).annotate(childes_count=Count('childes))