如何从递归关系中获取第一个子项



我一直在使用

def get_all_children(self, include_self=True):
r = []
if include_self:
r.append(self)
for c in Cateogory.objects.filter(parent=self):
_r = c.get_all_children(include_self=True)
if 0 < len(_r):
r.extend(_r)
return r

获取对象的所有子对象,但是它也返回其子对象的所有个子对象。我怎么能只对第一个、直接的孩子?

您可以将所有Category作为parent返回,当前项使用:

def get_direct_children(self):
return Category.objects.filter(parent=self)

最新更新