depth relation search
I am looking for a "pythonic" / "orm-ic" solution for this problem...
Model Soldier
has a ManyToManyField to itself.
class Soldier(models.Model):
...
subordinates = models.ManyToManyField('Soldier', ...)
A
, B
and C
are Soldier
objects
They form kind of "c开发者_如何学Gohain of command" like so: A > B > C
B
is in A.subordinates.all()
C
is in B.subordinates.all()
What's the best way to get all subordinates of A
?
A.get_all_subordinates()
, that should return [B, C]
.
We don't know how many levels of this relation there is at runtime. (C
can have some subordinates of his own, B
can have siblings, etc.)
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.
精彩评论