[Answered ]-Depth relation search

2👍

If you model the superior <-> subordinate relation with a many-to-many relation, you’ll end up with a graph-like structure that can get arbitrary complex (e.g. circular relations). This will become very hard to query efficiently.

If you’re after a tree-like structure (which means that every Soldier has at most one direct superior), you could use django-mptt:

from django.db import models
from mptt.models import MPTTModel

class Soldier(MPTTModel):
    parent = models.ForeignKey('self', null=True, blank=True)

Getting all the subordinates is then as easy as

subordinates = soldier.get_descendants()

And the best thing about get_descendants: it causes exactly one query to get all descendants.

Leave a comment