Saqib Ali
Saqib Ali

Reputation: 12585

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

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

Upvotes: 2

Views: 2327

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174622

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

Upvotes: 2

falsetru
falsetru

Reputation: 369134

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.

Upvotes: 2

Related Questions