Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model structure for org charts

I need to build org charts for positions in a company (CTO answers to CEO, Developers answer to CTO, etc), and I need to create a friendly UI to reflect this. The UI part is not my concern right now, because if I build the backend right, the frontend will be easy.

So without using any fancy patterns (like graphs), what would be the best structure for a Position model (making my life easier when I fetch the org chart)?

So far I've thought of something like the following, but having a parent foreign key to itself won't help me much if I need to go 10 levels deep in the org chart.

class Position(models.Model):
    name = models.CharField(max_length=100)
    company = models.ForeignKey(Company)  # irrelevant
    level = models.PositiveSmallIntegerField()  # depth level (not sure if I need this since I have parent_position)
    parent_position = models.ForeignKey("self")

PS. Earlier in my question I wanted to avoid using graphs and such, simply because I have zero knowledge about them, and am on a tight schedule. Would learning and using graphs be a lot of help in this case?

like image 941
Eduard Luca Avatar asked Nov 17 '25 08:11

Eduard Luca


1 Answers

You could use django-mptt package for the project. It would compose your HR part as a tree structure and query subtrees in one batch without traversing the tree. Something like this should get you started(nothing near production obviously):

from mptt.models import MPTTModel, TreeForeignKey, TreeManager

class Organization(MPTTModel):
    name = models.CharField(max_length=255, unique=True)
    members = models.ManyToManyField(User)
    parent = TreeForeignKey('self', related_name='children')
    objects = TreeManager()
like image 66
Shang Wang Avatar answered Nov 19 '25 10:11

Shang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!