且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

所有孩子的Django自递归外键过滤器查询

更新时间:2023-02-02 23:37:22

您始终可以向模型添加递归函数:

You can always add a recursive function to your model:

根据 SeomGi Han 进行更正

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

仍然按照errx的建议推荐mptt.

2021 年,因为这个答案仍然受到关注:/

2021 since this answer is still getting attention :/

改用 django-tree-queries