Edgar Navasardyan
Edgar Navasardyan

Reputation: 4501

How to calculate the difference between two context variables in Django template

Consider a model:

class TempReport(models.Model):
    id = models.AutoField(primary_key=True)
    cost = models.FloatField()
    revenue = models.FloatField()
    # Some other fields not relevant to topic
    class Meta:
        managed = False
        db_table = 'temp_report'
        unique_together = (('sale_point', 'date'), ('id', 'sale_point'),)
        @property
        def net_income(self):
            return self.revenue - self.cost

My goal is to calculate net income = revenue - cost The code for the template:

<tbody>
                {% for repdata in reporttable %}
                 <tr>
                    <td> {{ repdata.revenue }}</td>
                    <td> {{ repdata.cost }}</td>
                    <td> {{ repdata.net_income}}</td>
                 </tr>
                {% endfor %}
       </tbody>

...and the view

def tempreport(request):
    reporttable = TempReport.objects.values('id','cost','revenue')
    return render_to_response('report.html',
                            {'reporttable': reporttable},
                             context_instance = RequestContext(request))

I end up with an empty net_income even if no error message is present. Any ideas why this might be caused by ?

Upvotes: 0

Views: 833

Answers (1)

Alasdair
Alasdair

Reputation: 308879

Creating a property on the model should work. The indentation on your code is incorrect. The property should be a method of the model class, not the Meta class.

class TempReport(models.Model):
    id = models.AutoField(primary_key=True)
    cost = models.FloatField()
    revenue = models.FloatField()
    # Some other fields not relevant to topic
    class Meta:
        managed = False
        db_table = 'temp_report'
        unique_together = (('sale_point', 'date'), ('id', 'sale_point'),)
    @property
    def net_income(self):
        return self.revenue - self.cost

In your view, don't use values(), because that will return dictionaries rather than model instances, and you won't be able to access the property.

from django.shortcuts import render

def tempreport(request):
    reporttable = TempReport.objects.all()

    for r in reporttable:
        r.net_income = r.revenue - r.cost
    return render(request, 'report.html', {'reporttable': reporttable})

Note I've also updated the view to use render instead of the obsolete render_to_response.

Upvotes: 4

Related Questions