快速获取Django用户选项卡中特定节点的所有子用户

2024-09-27 02:15:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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]

Tags: django模型formodelmodelsprofileclassparent
2条回答
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 
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)

相关问题 更多 >

    热门问题