我有一个表,其中包含纬度和经度字段。
`
location.objects.annotate( distance =math.fabs(math.pow((math.sin(
F('latitude') - float(90.378770)) /2 )),2) +
math.cos(90.378770) * math.cos( F('latitude')) *
pow((math.sin( (F('longitude') - float(-59.826830)) /2)),2) )
).values_list('distance', flat=True)
`
在执行数据库查询时如何对数据执行此等效的数学运算并将值存储在列表中。
答案 0 :(得分:1)
Django支持使用Python常量,变量甚至其他表达式对查询表达式进行求反,加法,减法,乘法,除法,模运算以及幂运算。
要执行诸如sin和cos之类的三角运算作为查询表达式,您需要Func()
expressions才能将数据库函数包含在查询集中
from django.db.models import F, Func
class Sin(Func):
function = 'SIN'
class Cos(Func):
function = 'COS'
latitude = 90.378770
longitude = -59.826830
Location.objects.annotate(
distance=(
Sin((F('latitude') - latitude)/2)**2 +
(
Cos(F('latitude'))*Cos(latitude)*
Sin((F('longitude') - longitude)/2)**2
)
)
)