0

I have the following simplified model:

class Part(models.Model):
    identification = models.CharField(max_length=50)
    parent_part = models.ForeignKey('Part',blank=True,null=True)
    weight = models.DecimalField(max_digits=12,decimal_places=3)

As you can see, a Part can be composed of others parts, each with it's own weight, forming a tree. Of course, the top level part (root) will have no "parent_part".

What I'm struggling right now it to implement a way to sum all the weight of all the subparts.

All my ideas so far fall in some form of recursion that I know that should be avoided.

BAsed in my knowledge, I think that the proper solution would be through Model Managers but I'm not sure how.

Any suggestions?

rrb_bbr
  • 2,966
  • 4
  • 24
  • 26

1 Answers1

1

Adjacent list (parent / children relationship) is one way of modeling tree structure, but it's not the only way, and it can be inefficient in certain tree operations, such as sub-tree aggregation as in your example.

If performances is critical for your application, and the query pattern is read-intensive, consider using an alternative model such as nested set.

Possibly related question,

Database Structure for Tree Data Structure

Community
  • 1
  • 1
liuyu
  • 1,279
  • 11
  • 25