Django treebeard подсчет каждого ребенка

Я использую django-treebeard для создания дерева Структур (что-то вроде папок). Каждая Структура может содержать Ресурс. Когда я составляю список структур, мне нужно знать, сколько ресурсов находится в текущей структуре и ее дочерних структурах.

Есть ли способ суммировать их с помощью агрегации?

Пример:

- RootStructure
   - ChildStructure
        - Resource1
        - Resource2



return Structure.get_root_nodes().annotate(resources_number=Count("resource")) 
resources_number = 0 (i want to get 2 because ChildStructure have 2 Resources but this Count will not work)

return parent_obj.get_children().annotate(resources_number=Count("resource"))
resources_number = 2 when parent_obj is RootStructure

Вот мои модели:

class Structure(MP_Node):
    objects = StructureManager()

    name = models.CharField(max_length=100)
    description = models.CharField(max_length=500, blank=True, default="")
   

    class Meta(MP_Node.Meta):
        ordering = ("path",)


class StructureResource(models.Model):
    resource_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    structure = models.ForeignKey(
        Structure, on_delete=models.CASCADE, related_name="resource"
    )
    resource_id = models.IntegerField()
    resource_object = GenericForeignKey("resource_type", "resource_id")
Вернуться на верх