首页 > 解决方案 > 在 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 并使用信号将结果保存在同一模型上。出了点问题,因此结果没有保存在模型上

标签: djangodjango-modelsdjango-views

解决方案


我认为您需要在计算函数中传递保存变量的默认参数,如下所示:

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)


推荐阅读