问题
This question is related to this one.
My Django Model:
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. However when I try to print myIntB in the template below, nothing shows up. How can I access myIntB from the template? 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. And I need to use {% recursetree %} in the template file to display the tree structure inherent in a collection of myModels.
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>
来源:https://stackoverflow.com/questions/19763241/how-to-add-extra-data-to-a-django-mptt-model-for-display-in-template