我想从具体对象中递归地获得所有孩子,直到现在我有了这个。。
INFO:
id = 15的对象的子代-> [对象:ID:16,对象:ID:17]
id为17的对象的子代-> []
models.py:
class CustomModel(models.Model):
...
parent = models.ForeignKey('self', related_name='child', blank=True, null=True, on_delete=models.SET_NULL)
def get_child(self, childs=[]):
child = CustomModel.objects.filter(parent_id=self.id).first()
if childs is None:
childs = []
if child is not None:
childs.append(child.id)
child.get_child(childs)
else:
result = CustomModel.objects.filter(id__in=childs)
print(result)
return result
view.html:
def detail(request, id=None):
element = CustomModel.objects.get(id=id)
return render(request, ‘file.html’, {
‘element’: element
})
file.html:
{{ element.get_child }}
或
{% for child in element.get_child %}
在打印调试点上,我可以看到所有子对象,但是在模板中显示为无]
有人可以帮我吗?大家新年快乐。
我想从具体对象递归获取所有子对象,直到现在我有了这个。.INFO:对象1 id:15 parent_id:无object id:16 parent_id:15 object id:17 parent_id:16 ...
已解决!
您可能需要从此更改代码