从同一个 table 中获取具有级别的父子关系

Fetch parent child relation with level from the same table

嗨,我是 django 的新手,python。

# function for fecthing the child
def get_childern(request, username):
    Q = list(Profile.objects.filter(sponsor_id__exact=username))
    populate(request, Q, username)


# Iterate the Queryset 
def populate(request, quesryset, username):
    if quesryset:
        messages.success(request, username+' has '+str(len(quesryset))+' child')
        messages.info(request, quesryset)
        for user in quesryset:
            get_childern(request, user.user_id)
    else:
        messages.warning(request, 'User '+username+' has no child')
        return False

# calling all children 
get_childern(request, username)

我想添加级别,如何进一步细分。

请帮助我,投入大量时间和精力。 感谢大家:)

我找到了解决方案如果有人想提供一些反馈或想法以获得更好的解决方案,请在此处发表评论。感谢所有人:)

# for return a child query-set
def get_childern(request, username):
    Q = Profile.objects.filter(sponsor_id__exact=username)
    return Q


level = int(1) # set according to need 
tree_set = {}


# iterate the queryset and call itself
# recursion - set the level to control 
def iterate_object(request, quesryset):
    global tree_set
    outer_count = int(0)
    inner_count = int(0)
    level_tree = []
    for users in quesryset:
        outer_count = outer_count + 1
        # messages.info(request, users.user_id)
        Qs = get_childern(request, users.user_id)
        if Qs:
            for child in Qs:
                inner_count = inner_count + 1
                level_tree.append(child)

            # count = count + len(Qs)
            # messages.warning(request, Qs)
        else:
            # messages.warning(request, 'No child')
            pass
    else:
        # messages.error(request, 'Total child at level 2 => ' + str(count))
        # messages.info(request, outer_count)
        # messages.success(request, inner_count)
        global level
        level = level + 1
        # set the numeric value to control the level
        if level <= 10: 
            tree_set.update({level: level_tree})
            iterate_object(request, level_tree)
            return tree_set
        else:
            # messages.warning(request, 'else part')
            pass