使用django上相同型号的信号保存
我想在图1上合并这些方法,这样我就可以得到图2,并使用信号将结果保存在同一个模型上。出现问题,因此结果未保存在模型上 图1:使用django上相同型号的信号保存,django,django-models,django-views,Django,Django Models,Django Views,我想在图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 = model
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,并使用信号将结果保存在同一个模型上。出现问题,因此结果未保存在模型上我认为您需要在calculate func中为save变量传递一个默认参数,如下所示:
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)
然后在信号函数中,您可以再次通过保存,如下所示:
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)我尝试过,但一半的解决方案是,当我创建发票时,它不会保存其字段上的值,但我会更新发票而不做任何更改,它会更新发票,表上的值也会更新为。也许您需要尝试更改calculate func中的var,并改用它。事实上,calculate func应重新运行未定义的变量我已发布了可能的解决方案,请检查!