Django self-recursive foreignkey filter query for all childs

You can always add a recursive function to your model:

EDIT: Corrected according to SeomGi Han

def get_all_children(self, include_self=True):
    r = []
    if include_self:
        r.append(self)
    for c in Person.objects.filter(parent=self):
        _r = c.get_all_children(include_self=True)
        if 0 < len(_r):
            r.extend(_r)
    return r

(Don’t use this if you have a lot of recursion or data …)

Still recommending mptt as suggested by errx.

EDIT: 2021 since this answer is still getting attention :/

Use django-tree-queries instead!

Leave a Comment