I have models as,
class Invoice():
class Entry():
invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT, related_name='entries')
amount = CurrencyField()
I have to calculate total amount for a invoice by backward relation
I have models as,
class Invoice():
class Entry():
invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT, related_name='entries')
amount = CurrencyField()
I have to calculate total amount for a invoice by backward relation
A CurrencyField [GitHub] stores a currency, like 'USD', not an amount of a given currency, so not 5 USD. You need a MoneyField to do this.
The modeling thus should look like:
from django.db import models
from djmoney.models.fields import MoneyField
class Invoice(models.Model):
pass
class Entry(models.Model):
invoice = models.ForeignKey(
Invoice, on_delete=models.PROTECT, related_name='entries'
)
amount = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
You can sum up the currency of an invoice with:
from django.db.models import Sum
my_invoice.entries.aggregate(total=Sum('amount'))['total']
this will only work if the amounts all have the same currency.