Reputation: 332
Does anyone know a way in Django to calculate a field from the values of other property fields? Here's my invoice model:
class Invoice(models.Model):
types = [
('customer', 'Customer'),
('supplier', 'Supplier')
]
number = models.CharField(max_length=30)
date_invoice = models.DateTimeField('Date', default=timezone.now())
comment = models.TextField(default=get_default_invoice_comment())
type = models.CharField(max_length=20, choices=types, default='customer')
partner_id = models.ForeignKey(
'Partner', default=1, on_delete=models.CASCADE)
currency_id = models.ForeignKey(
'Currency', default=1, on_delete=models.CASCADE)
@property
def tax_amount(self):
total = 0
for line in self.invoiceline_set.all():
total += line.tax_amount
return total
@property
def subtotal(self):
total = 0.0
for line in self.invoiceline_set.all():
total += line.subtotal
return total
@property
def total(self):
return self.subtotal + self.tax_amount
def __unicode__(self):
return self.number
The tax_amount and subtotal on the InvoiceLine model are property fields. The subtotal gets calculated fine, however the total does not as it depends on another property field (tax_amount, which also does not get calculated properly) and I guess Django does not know in what order to perform the calculations? To reiterate, the problem is the total and tax_amount fields are always empty (even if the fields they are calculated from are not).
Upvotes: 0
Views: 1203
Reputation: 332
The problem was that some invoice_lines did not have a tax_id (because they were added before that was implemented) and the tax_amount field on the InvoiceLine is a property field that is calculated by the rate on the related Tax object. So the tax_amount on those lines wasn't able to be computed as it tried to sum floats and None types.
Upvotes: 1