0

I'm using django-treebeard to create tree of Structures (some kind of folders). Each Structure could contain a Resource. When I list my Structures I need to know how many Resources are in current Structure and it's children.

Is there a way to Sum them with aggregation?

Example:

- 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

Here are my models:

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")
Marshall
  • 65
  • 1
  • 6

0 Answers0