Order Django queryset by value closest to 0

Question:

I have a queryset that is returning a list of entries that are tied for the lead in a contest…


    leaders = ContestEntry.objects.filter(name=game, wins=wins)

After I get this data I need to put them in order by a second field (‘difference’) as a tie breaker. The problem I can’t figure out is I need the order to be by the number closest to 0. There will be a lot of negative and positive numbers.

Thanks for your help

Asked By: Ryan Thomas

||

Answers:

Using this answer the following code should give you the right results.

from django.db.models import Func, F

leaders = ContestEntry.objects.filter(name=game, wins=wins).annotate(abs_diff=Func(F('difference') - difference, function='ABS')).order_by('abs_diff').first()
Answered By: MSpruijt

You can use Django’s Abs function [Django-doc]:

from django.db.models import F
from django.db.models.functions import Abs

ContestEntry.objects.filter(name=game, wins=wins).order_by(
    abs_diff=Abs(F('difference') - difference).asc()
).first()
Answered By: willeM_ Van Onsem