如何添加额外的数据到Django模型显示在模板? [英] How to add extra data to a Django model for display in template?

查看:168
本文介绍了如何添加额外的数据到Django模型显示在模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django模型:

My Django Model:

class myModel(models.Model):
    myIntA = models.IntegerField(default=0)   

我的观点:

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

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

以上是否合法?您可以看到我向每个myModel对象添加了一个变量myIntB。
但是当我尝试在下面的模板中打印myIntB时,没有任何显示。
如何从模板访问myIntB?这不是我为这个模型定义的一个领域,也不是我想要的。我只是希望在渲染这个特定的模板时,使用这个额外的变量来增加我的模型。

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.

我的模板:

        {% for currModel in myModels %}
            {{currModel.myIntA}}<br/>
            {{currModel.myIntB}}<br/>
        {% endfor %}        


推荐答案

不会做你所想的;尝试这样做:

No that won't do what you are thinking; try this instead:

enriched_models = []
myModelList = myModel.objects.all()
for i in myModelList:
    enriched_models.append((i, 'foo'))

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

然后在您的模板中:

{% for currModel,extra in myModels %}
   {{ currModel.myIntA }}<br/>
   {{ extra }}<br/>
{% endfor %}      

这篇关于如何添加额外的数据到Django模型显示在模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆