【问题标题】:django-mptt model instance does not support indexingdjango-mptt 模型实例不支持索引
【发布时间】:2016-01-29 07:30:38
【问题描述】:

我正在尝试使用 django-mptt 实现一个简单的文件浏览器应用程序

这是我的models.py

class RootMPTT(MPTTModel):
    name = models.CharField(max_length =255)
    parent = TreeForeignKey('self',null=True,blank=True,related_name='children',db_index=True)

class Doc(models.Model):
    file = models.FileField(upload_to=set_upload_path_MPTT)
    belongs_to = models.ForeignKey(RootMPTT)

我正在尝试使用教程部分中的代码在 html 中显示树视图

  {% load mptt_tags %}
<ul>
    {% recursetree nodes %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

我从 django 收到以下错误

'RootMPTT' object does not support indexing

主要是因为'nodes'变量在下面

nodes = RootMPTT.objects.get(pk=casenum)

如果我把它改成

nodes = RootMPTT.objects.all()

html 渲染得很好。但我只需要获取单个节点的后代,而不是所有根节点。

我想我可以通过获取get_children 方法来获取孩子并在 html 中手动显示它们。但想知道是否有使用递归树的方法

【问题讨论】:

    标签: python django django-mptt


    【解决方案1】:

    recursetree 接受查询集或节点列表,而不是单个节点。如果您只想显示一棵树,只需创建一个仅包含该树的查询集:

    nodes = RootMPTT.objects.get(pk=casenum).get_descendants(include_self=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多