Wreeecks
Wreeecks

Reputation: 2274

Django Queryset absolute value of the annotated field

How do I get the absolute value of the annotated field? I tried the code below but it did't work.

queryset.annotate(relevance=abs(F('capacity') - int( request.GET['capacity']) ) ).order_by('relevance')

Error:

TypeError: bad operand type for abs(): 'CombinedExpression'

Thanks in advance!

Upvotes: 10

Views: 4701

Answers (2)

Nwawel A Iroume
Nwawel A Iroume

Reputation: 1369

Using your own django function, you could do

from django.db.models.expressions import Func, Value

class ABS(Func):
    
    function = "ABS"

queryset.annotate(relevance=ABS(F('capacity') - Value(int(request.GET['capacity']))))

Upvotes: 1

T.Tokic
T.Tokic

Reputation: 1254

You can try with func expressions:

from django.db.models import Func, F

queryset.annotate(relevance=Func(F('capacity') - int(request.GET['capacity']), function='ABS'))

Upvotes: 16

Related Questions