Parent / Child Hierarchy / Nested Sets, in Python / Django

I am using Django / Python, but the pseudo code is definitely acceptable here.

Working with some pre-existing models, I have Employee, each of which has Supervisor, which is essentially a relation of the type of foreign key to the other Employee.

If the Employee / Supervisor hierarchy looks something like this:

Every employee has ONE supervisor. This Supervisor may have one or more Workers "below", and he has his own Supervisor. Getting my upline should return my boss, his manager, her manager, etc., until you get an employee who doesn't have a manager.

Without going into hog-wild and installing new applications to manage these relationships, since this is an existing code base and project, I wonder how "pythonic" or the right way to implement the following functions:

def get_upline(employee): 
    # Get a flat list of Employee objects that are
    # 'supervisors' to eachother, starting with 
    # the given Employee. 
    pass


def get_downline(employee):
    # Starting with the given Employee, find and 
    # return a flat list of all other Employees 
    # that are "below". 
    pass

I feel that there may be a somewhat simple way to do this with Django ORM, but if not, I will accept any suggestions.

I have not thoroughly tested Django-MPTT, but if I can keep the models in tact and just get more functionality, it's worth it.

+3
source share
2 answers

, django-mptt; parent , django-mptt mptt automaitcally, : mptt.register(MyModel).

, "", . , . / .., !

+2

, - . :

def get_upline(employee):
    if self.supervisor:
        return [employee] + self.supervisor.get_upline()
    else:
        return [employee]

def get_download(employee):
    l = [employee]
    for minion in self.minion_set.all():
        l.extend(minion.get_download())
    return l
0

Source: https://habr.com/ru/post/1752326/


All Articles