Reputation: 145
I would like to merge these methods on figure_1 so i can get the figure_2 and use signals to save the results on the same model. something is wrong so results are not saved on the model
figure_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
figure_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)
I would like to merge these methods on figure_1 so i can get the figure_2 and use signals to save the results on the same model. something is wrong so results are not saved on the model
Upvotes: 0
Views: 37
Reputation: 300
I think you need to pass in the calculate func a default parameter for save variable, like this:
def calculate(self, save=False):
Then in signal func you can pass again save, like this:
def invoice_pre_save(sender, instance, *args, **kwargs):
instance.calculate(save=False)
pre_save.connect(invoice_pre_save, sender=Order)
And now you should be able to call calulate(save=True)
Upvotes: 1