且构网

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

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

更新时间:2023-02-02 23:11:44

您可以随时向模型添加递归函数:



编辑:根据SeomGi Han更正

  def get_all_children(self,include_self = True) 
r = []
如果include_self:
r.append(self)
for Person.objects.filter(parent = self):
_r = c。 get_all_children(include_self = True)
如果0< len(_r):
r.extend(_r)
return r

(如果您有很多递归或数据,请不要使用此...)



仍然建议由errx建议的mptt。


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.