简体   繁体   中英

Fetch parent child relation with level from the same table

Hi I'm new with django and 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)

and I want to add the level, how to break it down further.

Please help me, invest lots of time and mind. Thanks to all:)

I found the solution if anyone wants to give some feedback or idea for a better solution, comment here. Appreciate to all:)

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM