0

On the model page, I created a property called nzd_price, which is not really a field, but a property. On a templatetags page, I tried to aggregate the sum all the rows of a column from nzd_price for a new row with the name Total:

  • models.py:
class BrazilBill(models.Model):
  item = models.CharField('item', max_length = 50)
  price = models.DecimalField('price', max_digits = 10, decimal_places = 2)

  @property
  def nzd_price(self):
      return round(float(self.price) * 0.29, 2)
  • templatetags/total_price.py:
from django import template
from django.db.models import Sum
from financial_planning.models import BrazilBill

register = template.Library()

@register.filter
def brazil_bill_total_brl(value):
    return BrazilBill.objects.aggregate(Sum('price')).get('price__sum')

@register.filter
def brazil_bill_total_nzd(value):
    return BrazilBill.objects.aggregate(Sum('nzd_price')).get('nzd_price__sum')

The error:

FieldError at /financial-planning/
Cannot resolve keyword 'nzd_price' into field. Choices are: id, item, price

Based on Calculate the sum of model properties in Django, I also tried:

@register.filter
def brazil_bill_total_nzd(value):
    return BrazilBill.objects.aggregate(Sum('brazilbill__nzd_price'))
Oo'-
  • 203
  • 6
  • 22
  • 1
    You can not filter/annotate/aggregate a property, since these properties do not exist in the database, and thus this can not be evaluated with a database query. – Willem Van Onsem Jun 19 '21 at 10:34
  • That plus won't the conversion be similar anyway mathematically? `brazil_bill_total_brl * 0.29` will give you what you want I believe? But even further this kind of static currency conversion is very wrong, as this means you will have to periodically keep updating your code... – Abdul Aziz Barkat Jun 19 '21 at 10:37
  • Have a look at this [grid](https://djangopackages.org/grids/g/currencies/) which shows some packages that help dealing with currencies in Django. – Abdul Aziz Barkat Jun 19 '21 at 10:42
  • I am already using Forex Python, but I put that because of KISS. – Oo'- Jun 19 '21 at 10:42

1 Answers1

0

You need to annotate this property first.

(
     BrazilBill.objects.annotate(nzd_price=F("price")*0.29)
     .aggregate(Sum("nzd_price"))
)
Mark Rofail
  • 808
  • 1
  • 8
  • 18