recursetree中的Django MPTT最大元素
有没有一种方法可以使用Django MPTT的recursetree中的Django MPTT最大元素,django,django-templates,django-mptt,mptt,Django,Django Templates,Django Mptt,Mptt,有没有一种方法可以使用Django MPTT的{%recursetree%}表示部分树,而不从数据库中检索整个树?我需要显示深度优先搜索遇到的前20个节点 其中任何一个(不检索完整树)都会导致异常: # resulting querySet passed to {% recursetree %} in template Thing.objects.all()[:20] # directly sliced in template {% recursetree all_nodes|slice:":
{%recursetree%}
表示部分树,而不从数据库中检索整个树?我需要显示深度优先搜索遇到的前20个节点
其中任何一个(不检索完整树)都会导致异常:
# resulting querySet passed to {% recursetree %} in template
Thing.objects.all()[:20]
# directly sliced in template
{% recursetree all_nodes|slice:":20" %}
AssertionError在呈现时:一旦获取了一个切片,就无法对查询重新排序
另一方面,这确实有效,但检索整个树:
# resulting querySet passed to {% recursetree %} in template
list(Thing.objects.all())[:20]
如何在不从DB检索整个树的情况下执行此操作?MPTT使用预排序(这已经是深度优先搜索了)。因此,您只需在将查询集传递给recursetree之前为其添加一个限制即可
如果将查询集传递给recursetree
,MPTT将调用order\u by()
,但如果传递列表,则无法执行此操作。这种行为有点令人困惑,也给其他人带来了麻烦
我已经创建了一个解决方案
同时,您可以在list()调用之前进行切片:
这将完成数据库中的限制,然后将查询集转换为列表,您可以将其传递到
recursetree
,而无需它尝试重新排序。谢谢,但这在{%recursetree%}
中给出了一个例外。请看我更新的问题。确实如此。编辑以修复此问题。
list(Thing.objects.all()[:20])