python - Django "extra" query -
i have following model structure in models.py, items , 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 write query in views.py following each item:
- the total of current (active) offers item
- the percentage of target has been met offers item (i.e. [the total (1)]/target_amount * 100)
i have been trying achieve "extra" follows (using postgres):
items = item.objects.filter(status='a').extra( select={ 'total_amount' : 'select coalesce(sum(amount),0) myapp_offer myapp_offer.item_id = myapp_item.id , myapp_offer.status = \'a\'', 'percentage_met' : '(((select coalesce(sum(amount),0) myapp_offer myapp_offer.item_id = myapp_item.id , myapp_offer.status = \'a\') / target_amount) * 100)' } ) now first select (total_amount) working correctly , returns expect, percentage_met 0. can me out why?
edit: should have mentioned want able order_by percentage_met
you don't need extra this. use aggregation:
from django.db.models import sum items = item.objects.filter(status='a').annotate(total_amount=sum('offer__amount')) percentage_met per object, anyways, can method on 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
Comments
Post a Comment