快速获取django用户表中特定节点的所有子用户

时间:2016-12-28 12:59:16

标签: python django

我有django模型:

class Profile(models.Model): 
    user = models.OneToOneField(User)
    parent = models.ForeignKey(User, related_name='parent_user_for_profile')

如何创建返回所有子用户的函数。

例如See picture of hierarchy

For n12 - [n122, n1211б n121, dsf]
For n1 - [n12, n11, n122, n1211, n121, dsf]
For n2 - [n21, n212]

2 个答案:

答案 0 :(得分:0)

def get_children_of_user(parent):
    children = Profile.objects.filter(parent=parent).values_list('user', flat=True)
    for child in children:
        children += get_children_of_user(child)
    return children 

答案 1 :(得分:0)

def get_children_of_user(parent_id):
    children = list(Profile.objects.filter(parent_id=parent_id).values_list('user_id', flat=True))
    for child in children:
        children += get_children_of_user(child)
    return list(children)