Django self-recursive foreignkey filter query for all childs
sunn0's suggestion is great idea, but get_all_children() returns weird results. It returns something like [Person1, [Person3, Person4], []]. It should be changed to like below.
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
You should read about Modified preorder tree traversal. Here is django implementation. https://github.com/django-mptt/django-mptt/
If you know the max depth of your tree, you could try something like this (untested):
Person.objects.filter(Q(parent=my_person)|Q(parent__parent=my_person)| Q(parent__parent__parent=my_person))
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!