hansonmbbop
hansonmbbop

Reputation: 83

Django sum total price from table items and table transaction

I have two tables, items and transaction, how do i calculate the total price, and displaying the total price in templates

class Items(models.Model):
    items_name = models.CharField(max_length=50)
    price = models.PositiveIntegerField()
    def __str__(self):
        return self.items_name
class Transaction (models.Model):
    items = models.ForeignKey(Items, on_delete=models.CASCADE)
    qty = models.PositiveIntegerField()

    def total_price(self):
        total = self.qty * self.items.price
        return total
    total_price = models.PositiveIntegerField(total_price)

Here is the View

def transaction(request):
    transactions=Transaction.objects.all()

    context={'transactions':transactionss}
    return render(request,'app/transaction.html',context)

here is my template

{% for transaction in transactions %}


                <tr>
                    <td>{{transaction.item}}</td>
                    <td>{{transaction.qty}}</td>


                    <td><a class='btn btn-sm btn-info' 
                        href="#">
                        Update</a></td>
                    <td><a class='btn btn-sm btn-danger' 
                        href="#

                        ">Delete</a></td>
                </tr>
                {% endfor %}    
                <tr><td>
                    {{total_price}}
                </td></tr>

I want to display the full total_price of all transactions, for example item 1 with price 100 * quantity 2 and item 2 with price 200 * quantity 3 . then the total price would be 200 + 600 = 800. I want to display the 800 in the template.

Upvotes: 0

Views: 485

Answers (1)

Jim
Jim

Reputation: 2300

Take care of this in your view. You're already grabbing all the transactions, might as well total up the total_price then:

views.py

def transaction(request):
    total = 0
    transactions = Transaction.objects.all()
    for t in transactions:
        total += t.total_price()
    context = { 'transactions': transactions, 'total_price': total }
    return render(request, 'app/transaction.html', context)

This will loop through the transactions, get the result of the total_price function, and add it to a running total. You send that total in the context as total_price and you can call it in your view template.

One more thing:

Remove the line total_price = models.PositiveIntegerField(total_price) - you already have the function total_price calculating the total, this is defining a model field you don't want or need.

Your model should look like:

class Transaction (models.Model):
    items = models.ForeignKey(Items, on_delete=models.CASCADE)
    qty = models.PositiveIntegerField()

    def total_price(self):
        total = self.qty * self.items.price
        return total

Upvotes: 1

Related Questions