Django Queryset absolute value of the annotated field

此生再无相见时 提交于 2019-12-14 01:17:43

问题


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!


回答1:


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'))


来源:https://stackoverflow.com/questions/49868706/django-queryset-absolute-value-of-the-annotated-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!