Dean Christian Armada
Dean Christian Armada

Reputation: 7364

Django order by via custom method

My custom method is actually a calculation and I am trying to avoid ordering via manager and if possible just use order_by. Is there a way or a one line syntax to achieve this? Here is my model:

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

Upvotes: 0

Views: 45

Answers (1)

Sayse
Sayse

Reputation: 43300

You're looking to annotate

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

See Using F() with annotations

Upvotes: 4

Related Questions