django - 在 django 上保存相同型号的信号
问题描述
我想在图 1 上合并这些方法,这样我就可以得到图 2 并使用信号将结果保存在同一模型上。出了点问题,因此结果没有保存在模型上
图1 :
class Invoice(models.Model):
date = models.DateField(default=timezone.now)
amount_gtotal = models.DecimalField(max_digits=20, decimal_places=2, default=0)
amount_gtax = models.DecimalField(max_digits=20, decimal_places=2, default=0)
amount_gamount = models.DecimalField(max_digits=20, decimal_places=2, default=0)
def amount_gtotal(self):
items = self.invoiceitem_set.all()
amount_gtotal = 0.00
for item in items:
amount_gtotal += item.price * item.quantity
return amount_gtotal
def amount_gtax(self):
items = self.invoiceitem_set.all()
amount_gtax = 0
for item in items:
amount_gtax += item.price_sell * item.quantity * item.vat
return amount_gtax
def amount_gamount(self):
amount_gamount = self.amount_gtotal() + self.amount_gtax()
return amount_gamount
图_2:
def calculate(self):
invoiceitems = self.invoiceitem_set.all()
amount_gtotal = 0
amount_gtax = 0
amount_gamount = 0
for invoiceitem in invoiceitems:
amount_gtotal += item.price * item.quantity
amount_gtax += item.price_sell * item.quantity * item.vat
amount_gamount += amount_gtotal + amount_gtax
totals = {
'amount_gtotal': amount_gtotal,
'amount_gtax': amount_gtax,
'amount_gamount': amount_gamount,
}
for k,v in totals.items():
setattr(self, k, v)
if save == True:
self.save()
return totals
def invoice_pre_save(sender, instance, *args, **kwargs):
instance.calculate()
pre_save.connect(invoice_pre_save, sender=Invoice)
class InvoiceItem(models.Model):
invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.PROTECT)
price_sell = models.DecimalField(max_digits=20, decimal_places=2)
quantity = models.DecimalField(max_digits=20, decimal_places=2)
vat = models.DecimalField(max_digits=5, decimal_places=2)
我想在图 1 上合并这些方法,这样我就可以得到图 2 并使用信号将结果保存在同一模型上。出了点问题,因此结果没有保存在模型上
解决方案
我认为您需要在计算函数中传递保存变量的默认参数,如下所示:
def calculate(self, save=False):
然后在信号函数中你可以再次保存,如下所示:
def invoice_pre_save(sender, instance, *args, **kwargs):
instance.calculate(save=False)
pre_save.connect(invoice_pre_save, sender=Order)
现在你应该可以调用 calulate(save=True)
推荐阅读
- vsto - 保存 vsto Excel 后功能区消失
- python - VS Code Python + 黑色格式化程序参数 - python.formatting.blackArgs
- python - Django 是否可以为每个客户端使用相同的链接和数据库?
- bluetooth - Zebra QLN320 和 Zebra 打印站
- selenium - WebDriverException:未知错误:无法解压缩“文件”
- r - 具有离散 x 轴的 geom_density() 分组图不平滑
- arangodb - 将 MongoDB 聚合转换为 ArangoDB COLLECT
- kubernetes - Minikube Kubernetes:两个 pod 和服务
- javascript - 如何为此按钮添加“onclick”事件
- c# - 未知“?” 使用 ChromeDriver 从网站读取