gpt4 book ai didi

python - 如何在模板中显示递归数据?

转载 作者:行者123 更新时间:2023-11-28 00:02:20 25 4
gpt4 key购买 nike

我有一个 ForeignKey = 'self' 的模型,我想通过列表和子列表反射(reflect)数据库中的所有数据:

这是我的模型:

class Place(models.Model)
name = models.CharField(max_length=128, verbose_name='Place name', )
slug = models.SlugField(max_length=128, blank=True, null=True)
parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True)
role = models.CharField(max_length=20, choices=ROLE_CHOICES, null=True, blank=True)

最佳答案

Django template is not designed to handle complex logics. For example, you can't write nested logic by using include tag like this:

# foo.html
{% if nodes|iterable %}
<ul>
{% for x in nodes %}
{% include "foo.html" with nodes=x %}
{% endfor %}
</ul>
{% else %}
<li>{{ nodes }}</li>
{% endif %}

Because Django template nodes get parsed and compiled before they get rendered, and the compiling of the above code could fall into loops and fail by hitting maximum recursion depth.

Normally, a template tag just like {% nested nodes %}, which works like a view but belongs to the scope of Django template, is all you need.

Moreover, you could transform the data to a flat one through a filter, then loop over it easily:

{% for x in nodes|nested_to_flat %}
{% if x.start_nodes %}<ul>{% endif %}
{% if x.end_nodes %}</ul>{% endif %}
{% if x.start_node %}<li>{% endif %}
{% if x.end_node %}</li>{% endif %}
{% if x.is_data %}{{ x.data }}{% endif %}
{% endfor %}

# nested_to_flat
@register.filter
def nested_to_flat(nodes):
if isinstance(nodes, list):
yield {'start_nodes': True}
for node in nodes:
yield {'start_node': True}
for i in nested_to_flat(node):
yield i
yield {'end_node': True}
yield {'end_nodes': True}
else:
yield {'data': nodes, 'is_data': True}

This is similar to the idea of rendering a mptt tree or threaded comments.

关于python - 如何在模板中显示递归数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55934465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com