【问题标题】:mptt tree paginationmptt树分页
【发布时间】:2011-12-14 07:53:59
【问题描述】:

我想对 mpttmodel 实例进行简单的分页。我有这个模型:

class Thing(MPTTModel):
    text = models.TextField()
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

问题是,当我尝试检索具有偏移量的对象时,例如:

Thing.objects.all()[5:10]

{% recursetree things %} 模板标签引发异常:Caught AssertionError while rendering: Cannot reorder a query once a slice has been taken.

如何解决?

【问题讨论】:

  • 你试过 list(Thing.objects.all())[5:10] - 这可能有效,因为 Django 必须在切片之前获取所有数据。您的原始调用在 SQL 中使用了 LIMIT 和 OFFSET 子句。您可以在 python shell 中执行此操作,看看它是否有效。

标签: django django-mptt


【解决方案1】:

recursetree 标记需要一个未应用数组切片限制语法的查询集。

您可以使用model and manager instances 来构建更合适的查询集,或者调用recursetree 并遍历节点,将它们过滤掉,然后根据需要再次从其中调用recursetree 并使用选定的节点,但这是一个有点复杂。

现在,看起来你可以实现你想要的:

nodes = [node.get_descendants(include_self=True) 
         for node in Thing.objects.all()[5:10]]

在模板中:

{% for node in nodes %}
    {% recursetree node %}...{% endrecursetree %}
{% endfor %}

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2011-04-22
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多