2016-12-28 40 views
1

特定节点的所有subusers我的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] 

回答

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 
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) 
+0

当提供上,所以请也给了@OP的解释,以便更好地了解您的代码做和如何解决他们所面临的问题的答案。 – Jordan