如何解决Django:从不同的表获取值并计算字段
我想从“产品”中获取“重量”并计算html上所示的“ total_weight = weight * quantity”
class Product(models.Model):
code = models.CharField(max_length=64,unique=True)
name = models.CharField(max_length=64)
weight = models.DecimalField(max_digits=20,decimal_places=2)
class Invoice(models.Model):
date = models.DateField(default=timezone.now)
client = models.ForeignKey(Client,on_delete=models.CASCADE)
class InvoiceItem(models.Model):
invoice = models.ForeignKey('Invoice',on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
price = models.DecimalField(max_digits=20,decimal_places=2)
quantity = models.DecimalField(max_digits=20,decimal_places=2)
def total(self):
return round(self.price * self.quantity,2)
还有html:
{% for product in object.invoiceitem_set.all %}
<tr>
<td>{{product.product}}</td>
<td>{{product.price}}</td>
<td>{{product.quantity}}</td>
<td>{{product.total}}</td>
<td>{{product.weight}}</td>
<td>{{product.total_weight}}</td>
</tr>
解决方法
在发票模型中添加总重方法
def total_weight(self):
return self.product.weight * self.quantity
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。