Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django self-recursive foreignkey filter query for all childs

I have this model with a self referencing Foreign Key relation:

class Person(TimeStampedModel):     name = models.CharField(max_length=32)     parent = models.ForeignKey('self', null=True, blank=True, related_name='children') 

Now I want to get all the multi level children for a person. How do I write a Django query for it? It needs to behave like recursive function.

like image 622
Ahsan Avatar asked Jan 18 '11 14:01

Ahsan


1 Answers

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!

like image 50
sunn0 Avatar answered Sep 20 '22 13:09

sunn0