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.
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!
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