简体   繁体   English

如何为递归树模板标签将自定义数据添加到Django MPTT模型

[英]How to add custom data to Django MPTT model for recursetree template tag

This question about MPTT objects and usage of the {% recursetree %} template tag is related to this one . 有关MPTT对象和{%recursetree%}模板标签的用法的问题与相关。

My Django Model: 我的Django模型:

from mptt.models import MPTTModel, TreeForeignKey
class myModel(MPTTModel):
    myIntA = models.IntegerField(default=0)   
    myParent = TreeForeignKey('self', null=True, blank=True, related_name='children')

My View: 我的观点:

myModelList = myModel.objects.all()
for i in range(len(myModelList)):
    myModelList[i].myIntB = i

return render(
    request, 
    'myApp/myTemplate.html', 
    Context(
        {
            "myModels": myModelList,
        }
    )
)

Is the above legal? 以上合法吗? You can see that I added a variable myIntB to each myModel object. 您可以看到我向每个myModel对象添加了一个变量myIntB。 However when I try to print myIntB in the template below, nothing shows up. 但是,当我尝试在下面的模板中打印myIntB时,没有任何显示。

How can I access myIntB from the template? 如何从模板访问myIntB? It is not a field I have defined for this model, nor do I want it to be. 这不是我为此模型定义的字段,也不是我想要的字段。 I just want myModel to be augmented with this extra variable during rendering of this particular template. 我只希望在呈现此特定模板的过程中使用此额外的变量来增强myModel。 The problem is that I don't see anyway to do so with the recursetree template tag. 问题是我仍然看不到recursetree模板标记可以这样做。

My Template: 我的模板:

{% load mptt_tags %}
<ul>
    {% recursetree nodes %}
        <li>
            {{node.id}} {{node.myIntA} {{node.myIntB}}
            {% if not node.is_leaf_node %}
                <ul>
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

The recursetree tag calls .order_by on your queryset, if it's actually a queryset. 如果recursetree标记实际上是一个查询集.order_by在您的.order_by上调用.order_by

This copies the queryset, does another query and re-fetches all the objects from the database. 这将复制查询集,执行另一个查询,然后从数据库中重新获取所有对象。 Your extra attribute no longer exists on the new objects. 您的额外属性不再存在于新对象上。

The easiest way to fix this is probably to call list() on your queryset before passing it to recursetree . 解决此问题的最简单方法可能是在将queryset传递给recursetree之前在queryset上调用list() Then mptt will assume the ordering is already done and won't re-order the queryset. 然后,mptt将假定已完成排序,并且不会对查询集重新排序。

myModelList = list(myModel.objects.order_by('tree_id', 'lft'))
for i, obj in enumerate(myModelList):
    obj.myIntB = i

return render(
    request, 
    'myApp/myTemplate.html', 
    Context({"myModels": myModelList})
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM