0

Im fairly new to Django. Im using Django 2.

My model:

# Create your models here.
class Trade(models.Model):
    quantity = models.IntegerField()
    open_price = models.FloatField()
    commision = models.FloatField()
    exchange_rate_usdsek = models.FloatField()
    stock = models.ForeignKey(Stock, on_delete=models.CASCADE)
    user = models.ForeignKey(User, related_name='trades', on_delete=models.PROTECT)
    open_date = models.DateTimeField(auto_now_add=True, null=True)

    def get_absolute_url(self):
        return reverse('trade:detail',kwargs={'pk': self.pk})

    def __str__(self):
        return self.stock.name

My view

class IndexView(generic.ListView):
    template_name = 'trade/index.html'
    context_object_name = 'all_trades'
    #
    def get_queryset(self):
        return Trade.objects.all()
        #return Order.objects.all().prefetch_related('items')
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        return context

index.html

<h3>All stocks</h3>
<table class="table">
    <thead>
        <tr>
            <th>Stock</th>
            <th>Amount</th>
            <th>Open Price</th>
            <th>Commision</th>
            <th>USD/SEK</th>
            <th>Total sek</th>
        </tr>
    </thead>
    {% for trade in all_trades %}
        <tr>
            <td>{{trade.stock.name}}</td>
            <td>{{trade.quantity}}</td>
            <td>{{trade.open_price}} USD</td>
            <td>{{trade.commision}} SEK</td>
            <td>{{trade.exchange_rate_usdsek}}</td>
            <td>{{open_price * quantity * exchange_rate_usdsek}}</td>
        </tr>
    {% endfor %}
</table>

Now on my index.html I want to calculate and display a value. I make a calculation like this:

total_sek = open_price * quantity * exchange_rate_usdsek 

Do I have to calculate this in the views.py or in the index.html? Also how would I do this? I searched around and found something about filters but im not sure if that is the right way to do it

Sharpless512
  • 3,062
  • 5
  • 35
  • 60

1 Answers1

7

The easiest way is to just define this calculation as a property on the model:

class Trade(models.Model):

    # ...

    @property
    def total_sek(self):
        return self.open_price * self.quantity * self.exchange_rate_usdsek 

at which point you can simply

<td>{{ trade.total_sek }}</td>

in the template,

and trade.total_sek in Python code as required too.

AKX
  • 152,115
  • 15
  • 115
  • 172