Skip to content
Advertisement

Accessing property of model instance from list and add them together?

Say I have a model:

class Mymodel(models.Model)
property = models.IntegerField()

Say I have a function:

def func():
instance = Mymodel.objects.order_by('?')[0]
instance2 = Mymodel.objects.order_by('?')[0]
plan = [instance, instance2]
return plan

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:

{% if instancelist|length == 2 %}
    {{ instancelist.0.property|add:instancelist.1.property }}
{% else %}
    {{ instancelist.0.property|add:instancelist.1.property|add:instancelist.2.property }}
{% endif %}

And so on.

Advertisement

Answer

Found a work around to this:

In your template just use the |length filter along with an if statement:

{% if instancelist|length == 2 %}
    {{ instancelist.0.property|add:instancelist.1.property }}
{% else %}
    {{ instancelist.0.property|add:instancelist.1.property|add:instancelist.2.property }}
{% endif %}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement