Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 561
Wreeecks Avatar asked Apr 17 '18 01:04

Wreeecks


1 Answers

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'))
like image 154
T.Tokic Avatar answered Nov 15 '22 07:11

T.Tokic