I have some UserInvites, where an invite has from and to User properties.
E.g.,
UserInvite1.from = User1
UserInvite1.to = User2
UserInvite1b.from = User1
UserInvite1b.to = User4
UserInvite2.from = User2
UserInvite2.to = User3
UserInvite3.from = User2
UserInvite3.to = User5
Thus, User1 invited User2 and User4; User2 invited User3 and User5.
Given a list of those invites, e.g., [UserInvite1, UserInvite2, ... ], or another means of iterating over them(?), how can I generate a "hierarchical" (nested) list representing those invited?
E.g., starting with the "root" User1, I'd like a nested list as such:
>>> make_nest_list_from_invites([invites])
[User1, [User2, [User3, User5], User4]]
If you're familiar with Django, I'm trying to get from my "invites" to something hierarchical that I can feed to the Django template tag unordered_list
Clearly this is something like tree traversal, but I'm stumped at the moment. I tried some recursion-ey stuff, but kept ending up with an extra level of nesting in places that was throwing things off.
UPDATE: Example of something I tried
def tree_from_here(user):
children = get_children(user)
if children:
return [user, [tree_from_here(c) for c in children]]
else:
return user
Which gives:
>>> tree_from_here(User1)
[<User: 1>, [[<User: 2>, [<User: 3>, <User: 5>]], <User: 4>]]
Which is almost correct for my current set of users, with the exception that the nesting goes too deep in the second element.
I am trying for:
[<User: 1>, [<User: 2>, [<User: 3>, <User: 5>], <User: 4>]]
I feel like it's staring me in the face, but I am not sure how to return the right thing at the moment.
touser is the same root user you started with orNone.