2017-01-24 151 views
0

我的自定義方法實際上是一種計算,我試圖通過管理器避免排序,如果可能的話只使用order_by。有沒有一種方法或一行語法來實現這一點?這裏是我的模型:Django通過自定義方法排序

class Bet(models.Model): 


    provider = models.ForeignKey(Provider) 
    member = models.ForeignKey(Member) 
    game = models.ForeignKey(Game) 
    status = models.ForeignKey(Status) 
    bet_id = models.CharField(max_length=200) 
    bet_time = models.DateTimeField() 
    bet_amount = models.FloatField() 
    valid_bet_amount = models.FloatField() 
    settlement_amount = models.FloatField() 

    def get_profit(self): 
     return self.settlement_amount - self.valid_bet_amount 

回答

4

您正在尋找註釋

profit = F('settlement_ammount') - F('valid_bet_amount') 
my_query.annotate(profit=profit).order_by('profit') 

Using F() with annotations

+1

好傢伙!你很棒!謝謝! –

+0

@DeanChristianArmada - 不用擔心,這也可以作爲一條線,但我選擇將它分離爲一個單獨的變量,以避免代碼示例中的滾動條 – Sayse

+0

是的,我同意你的看法! –