所有孩子的Django自递归外键过滤器查询 [英] Django self-recursive foreignkey filter query for all childs

查看:32
本文介绍了所有孩子的Django自递归外键过滤器查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自引用外键关系的模型:

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

现在我想为一个人获取所有的多级子级.如何为它编写 Django 查询?它需要表现得像递归函数.

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:

根据 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

这篇关于所有孩子的Django自递归外键过滤器查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆