I have the following model structure in my models.py, with Items and Offers:
class Item(models.Model):
STATUS_CHOICES = (
('A', 'Active'),
('C', 'Cancelled'),
)
status = models.CharField(max_length=11, choices=STATUS_CHOICES)
target_amount = models.PositiveIntegerField()
...
class Offer(models.Model)
STATUS_CHOICES = (
('A', 'Active'),
('C', 'Cancelled'),
)
status = models.CharField(max_length=11, choices=STATUS_CHOICES)
amount = models.PositiveIntegerField()
item = models.ForeignKey(Item)
...
I want to write a query in my views.py to get the following for each Item:
- The total of the current (active) offers for this item
- The percentage of the target that has been met by offers for this item (i.e. [the total from (1)]/target_amount * 100)
I have been trying to achieve this with "extra" as follows (using postgres):
items = Item.objects.filter(status='A').extra(
select={
'total_amount' : 'select coalesce(sum(amount),0) from myapp_offer where myapp_offer.item_id = myapp_item.id and myapp_offer.status = \'A\'',
'percentage_met' : '(((select coalesce(sum(amount),0) from myapp_offer where myapp_offer.item_id = myapp_item.id and myapp_offer.status = \'A\') / target_amount) * 100)'
}
)
Now the first select (total_amount
) is working correctly and returns what I expect, but the percentage_met
is always 0. Can anyone help me out as to why?
Edit: Should have mentioned that I want to be able to order_by the percentage_met