【问题标题】:Django : get value from different table and calculate fieldsDjango:从不同的表中获取值并计算字段
【发布时间】:2020-08-24 23:31:29
【问题描述】:

我想从 'Product' 中获取 'weight' 并计算 'total_weight=weight*quantity',如 html 所示

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>

【问题讨论】:

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


    【解决方案1】:

    为 invoiceitem 模型添加总重量方法

       def total_weight(self):
            return  self.product.weight *  self.quantity
    

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 2021-10-19
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 2021-04-13
      • 2018-07-19
      相关资源
      最近更新 更多