[Answered ]-Django "extra" query

1👍

You don’t need extra for this. Just use aggregation:

from django.db.models import Sum

items = Item.objects.filter(status='A').annotate(total_amount=Sum('offer__amount'))

percentage_met is per object, anyways, so that can just be a method on your model:

class Item(models.Model):
    ...
    @property
    def percentage_met(self):
        if hasattr(self, 'total_amount'):
            return (self.total_amount / float(self.target_amount)) * 100
        return None

1👍

I don’t think the code above is the cleanest way to get the value you want, but, assuming for a moment that it is– I suspect the issue you are seeing is actually a problem with the division in SQL– an int/int getting floored to the nearest int, which in this case is zero. Sum is certainly an int; what is target_amount, and where is it coming from? Is it an int?

In Postgres:

select 2/100; 
?column? 
----------
        0
(1 row)

If so, cast one of the values:

select 2::numeric/100;
?column?        
------------------------
 0.02000000000000000000
(1 row)
👤Karmel

Leave a comment