Geodjango 距离查询未检索到正确的结果

Geodjango distance query not retrieving correct results

我正在尝试检索一些 post,具体取决于它们在地理上的接近程度。
正如您在代码中看到的那样,我正在使用 GeoDjango 并且代码是在视图中执行的。
问题是距离过滤器似乎完全被忽略了。

当我检查查询集上的距离时,我得到了预期的距离(1 米和 18 公里),但是 18 公里 post 不应该被检索到。

def get(self, request, format=None):
    latlon=request.query_params
    pnt = GEOSGeometry('SRID=28992;POINT(%s %s)'%(latlon['lat'],latlon['lon']))
    posts = Post.objects.filter(point__distance_lte=(pnt, D(km=1)))
    serialized = PostSerializer(posts, many=True)
    for post in posts:
        distance = pnt.distance(post.point)
        print("Km distance:",distance * 100)
    return JsonResponse(serialized.data, safe=False)

结果:

Km distance: 0.00015231546206626192
Km distance: 18.317378752081577
[18/Jul/2017 13:24:35] "GET /api/posts/?lon=5.8372264&lat=51.8125626 HTTP/1.1" 200 144

相同的 SRID?我经常使用它,但是

source = models.PointField(geography=True, srid=4326)

然后在经理内部:

def starts_within_range_of(self, my_start, distance):
    ret_value = self.filter(
        source__distance_lte=(my_start, distance))
    return ret_value

但总是用 4326

我认为您的问题出在您的点创建过程中 reverse order of lat and lon

作为旁注,我更喜欢使用 Point() 点创建方法:

ptn = Point(x=latlon['lon'], y=latlon['lat'], srid=28992)

根据此评论进行编辑:

I tried that initializer, it seems correct to me thank you. However it doesn't seem to have solved the issue. It almost looks as the default distance unit is decameters because this works correctly. posts = Post.objects.filter(point__distance_lte=(pnt, 0.05)) this searches within a range of 5km – Evan

由于上述没有解决您的问题,我假设 dwithin's know problem with Distance objects 也适用于 distance 查询。

如上面链接的解决方案所述,几何字段默认为 WGS84,其中 degrees 作为默认测量单位。

0.05 degrees ~= 5 km,这就是您的解决方案正常工作的原因。

也许应该通知 geodjango 团队?