How to add extra data to a Django model for display in template?

自古美人都是妖i 提交于 2019-12-11 01:58:25

问题


My Django Model:

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

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.

My Template:

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

回答1:


Replace following line:

myModelList = myModel.objects.all()

with:

myModelList = list(myModel.objects.all())

Otherwise, new queries are performed everytime you access myModelList[i]; you lose the change you made.


Alternatively, what you want is simply counter, you can use forloop.counter or forloop.counter0 in the template.




回答2:


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})

Then in your template:

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


来源:https://stackoverflow.com/questions/19762288/how-to-add-extra-data-to-a-django-model-for-display-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!