I have a database model with deeply nested children. I am trying to add add all of the underlying ids (of all levels) to a dictionary entry. My current code looks as follows:
children = obj.children
for child in children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
This code is fully functional, but the problem is fairly obvious. I don't want to keep writing the same code over and over again: it's ugly, impractical and not very maintainable. How would I do this?
Use a recursive function to run the same code on different children:
def add_children_ids(ids, children):
for child in children:
ids.append(child.id)
add_children_ids(ids, child.children)
children = obj.children
data['children_ids'] = []
add_children_ids(data['children_ids'], children)
Because ids is a mutable list, there's no need to return it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With