Say I have a model:
JavaScript
x
3
1
class Mymodel(models.Model)
2
property = models.IntegerField()
3
Say I have a function:
JavaScript
1
6
1
def func():
2
instance = Mymodel.objects.order_by('?')[0]
3
instance2 = Mymodel.objects.order_by('?')[0]
4
plan = [instance, instance2]
5
return plan
6
I want to use a for loop to add together the integers in the ‘property’ of the model instance and then output the sum into one of my templates?
I have tried the add filter but the problem is the amount of instances it will be adding together are dynamic so I can’t simply do myModel.0.property|add:myModel.1.property
Thanks in advance.
EDIT:
Found a work around to this:
In your template just use the |length filter along with an if statement:
JavaScript
1
6
1
{% if instancelist|length == 2 %}
2
{{ instancelist.0.property|add:instancelist.1.property }}
3
{% else %}
4
{{ instancelist.0.property|add:instancelist.1.property|add:instancelist.2.property }}
5
{% endif %}
6
And so on.
Advertisement
Answer
Found a work around to this:
In your template just use the |length filter along with an if statement:
JavaScript
1
6
1
{% if instancelist|length == 2 %}
2
{{ instancelist.0.property|add:instancelist.1.property }}
3
{% else %}
4
{{ instancelist.0.property|add:instancelist.1.property|add:instancelist.2.property }}
5
{% endif %}
6