This implementation should work
def get_family_tree(person): """ return a family tree for a Person object """ children = person.children.all() if not children:
Please note that this will require as many database queries as there are people. You can try to extract all the data into memory if you encounter performance problems.
The thought of recursion
One way to think about recursion is to start with the base case - that is, where the recursion ends. In your case, we know what a family tree looks like if a person has no children:
{ 'name': 'FirstPerson', 'children': [], }
Once you have the underlying code (s), think about the problem when you need to do the recursion once.
In your case, these would be parents with children, but not grandchildren. We know what each child family tree should look like - this is just a basic case! This leads us to a solution in which we return the parent name and list of each child family. I will cite something like:
{ 'name': FirstPerson, 'children': [<each element is a child family tree>] }
Edit
Django automatically generates reverse relationships for ForeignKey.
class Person(models.Model): .... parent = models.ForeignKey('self', related_name='children', blank=True, null=True) p = Person() p.children.all()
See https://docs.djangoproject.com/en/1.9/ref/models/fields/#foreignkey
source share