【问题标题】:Django sum total price from table items and table transaction来自表格项目和表格交易的 Django 总价
【发布时间】:2020-04-24 03:52:18
【问题描述】:

我有两张表,项目和交易,我如何计算总价,并在模板中显示总价

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)

这里是视图

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

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

这是我的模板

{% 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>

我想显示所有交易的完整总价格,例如价格为 100 * 数量 2 的商品 1 和价格为 200 * 数量 3 的商品 2。那么总价将是 200 + 600 = 800。我想在模板中显示 800。

【问题讨论】:

    标签: django django-models django-views django-templates


    【解决方案1】:

    在您看来,请注意这一点。您已经获取了所有的交易,不妨将total_price 加起来:

    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)
    

    这将遍历事务,获取total_price 函数的结果,并将其添加到运行总计中。您在上下文中将总数发送为total_price,您可以在视图模板中调用它。

    还有一件事:

    删除行 total_price = models.PositiveIntegerField(total_price) - 你已经有函数 total_price 计算总数,这是定义你不想要或不需要的模型字段。

    您的模型应如下所示:

    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
    

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 2014-04-03
      • 2020-01-19
      • 1970-01-01
      • 2020-09-26
      • 2018-03-05
      • 2019-12-23
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多