使用Tastypie和GeoDjango,我试图返回位于一个点1英里内的建筑物的结果。
TastyPie documentation表示距离查找还不受支持,但我发现有人可以使用它,例如StackOverflow上的this discussionthis discussion,但没有可应用的工作代码示例。
我尝试使用的想法是,如果我在URL的末尾附加GET命令,则会返回附近的位置,例如:

http://website.com/api/?format=json&building_point__distance_lte=[{"type": "Point", "coordinates": [153.09537, -27.52618]},{"type": "D", "m" : 1}]

但当我尝试的时候,我得到的是:
{"error": "Invalid resource lookup data provided (mismatched type)."}

我已经在Tastypie文档上翻了好几天了,只是不知道如何实现它。
我会提供更多的例子,但我知道它们都很糟糕。谢谢你的建议,谢谢!

最佳答案

成功了,这是给后人的一个例子:
在api.py中,创建如下所示的资源:

from django.contrib.gis.geos import *

class LocationResource(ModelResource):
    class Meta:
        queryset = Building.objects.all()
        resource_name = 'location'

    def apply_sorting(self, objects, options=None):
        if options and "longitude" in options and "latitude" in options:
            pnt = fromstr("POINT(" + options['latitude'] + " " + options['longitude'] + ")", srid=4326)
            return objects.filter(building_point__distance_lte=(pnt, 500))

        return super(LocationResource, self).apply_sorting(objects, options)

“building”字段在models.py中定义为PointField。
然后在资源的URL中附加以下内容,例如:
&latitude=-88.1905699999999939&longitude=40.0913469999999990

这将返回500米内的所有物体。

10-06 07:09
查看更多