计算 GeoDjango 中同一模型上字段之间的距离

Compute distance between fields on the same model in GeoDjango

我想计算 GeoDjango 中同一模型上两个字段之间的距离。这是我尝试这样做的方式:

posts = Post.objects.filter(location__distance_lte=(ref_location,D(km=F('i_move'))

其中 location 是一个 PointField,i_move 是一个浮点数。但是,这不起作用,django 抛出:

float() argument must be a string or a number, not 'F'

我也尝试先获取大数的距离,然后进行注释,然后将距离与字段进行比较:

Post.objects.filter(location__distance_lte=(ref_location, D(km=100))
                                          ).annotate(distance=Distance('location', ref_location)
                                            ).filter(distance=F('i_move'))

这根本行不通,不会抛出任何错误。

我找不到任何人在做类似的事情,尽管我认为这个问题不是最近发生的。

似乎无法通过使用 F 字段查找的传统方式来完成。我最终使用了额外的查询参数,以及 postgres 的 St_Distance_Sphere 函数,它实际上非常好,因为它 returns 以米为单位的距离:

posts = Post.objects.filter(....).extra(
   where=['ST_Distance_Sphere(location::geometry, ST_GeomFromText(%s)) <= i_move*1000'],
   params=[ref_location.wkt])

ref_location 是一个 django Point(),location 是一个 PointField,i_move 是一个浮点数。 Django Points 有一个 wkt 方法来获取它们的 wkt 表示。但是,由于 ST_Distance_Sphere 需要几何对象,因此应使用 postgres 强制转换“::”转换位置,并使用 ST_GeomFromText 函数 ref_location 转换位置。