For a quick and dirty solution re-using what you already have, you could try a recursive approach. The pseudo-code would be something like:
def returningchilds(Target_id):
direct_children = ... # Uses the code you already have
ret = list()
for id_ in direct_children:
children = returningchilds(id_)
if children:
ret.append([id_, children])
else:
ret.append([id_, None])
return ret
Basically, it re-runs returningchilds for each detected direct child for the given id. Note that I use the id_ variable in a generic way, it can represent just the index or the index + the name depending on the location in the code. Also note that it’s a quick-and-dirty solution, there would be tons ow ways to improve it and make it more robust.
I’m not familiar with database management in Python, but I assume there must be plenty of helpful libraries for this application. Maybe someone else will orient you towards such solutions.