我在我的models.py下面的模型結構,項目和優惠:Django的「額外」的查詢
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)
...
我想寫我的views.py查詢以獲得每個項目下面:
- 的電流(活性)的總提供此項目
- 已針對此項目滿足由優惠(靶的百分比,即/ TARGET_AMOUNT * 100 [由式(1)的總] )
我一直在試圖與「額外」來實現這一如下(使用的是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)'
}
)
現在第一選擇(total_amount
)是否正常工作,並返回我的期望,但percentage_met
始終爲0任何人都可以幫我解答爲什麼?
編輯:應該提到,我希望能夠在ORDER_BY percentage_met
這是真實的,但麻煩的是我想ORDER_BY percentage_met ..只是嘗試這樣做,我不似乎無法order_by財產:/ – JimJay
好吧,不要擔心..已經計算出如何使用sorted()按照http://stackoverflow.com/questions/981375/using-a- django-custom-model-method-property-in-order- – JimJay