Django通过自定义方法订购

时间:2017-01-24 08:01:01

标签: django

我的自定义方法实际上是一个计算,我试图避免通过管理器进行排序,如果可能的话,只需使用order_by。是否有方法或单行语法来实现这一目标?这是我的模特:

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

1 个答案:

答案 0 :(得分:4)

您正在寻找注释

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

请参阅Using F() with annotations