【问题标题】:How can I measure distance with tastypie and geodjango?我如何用美味派和 geodjango 测量距离?
【发布时间】:2026-01-09 03:55:02
【问题描述】:

使用 Tastypie 和 GeoDjango,我试图返回位于点 1 英里范围内的建筑物的结果。

TastyPie documentation 声明尚不支持距离查找,但我在 * 上找到了人们使其工作的示例,例如 this discussionthis discussion,但没有可以应用的工作代码示例。

我尝试使用的想法是,如果我将 GET 命令附加到 URL 的末尾,则返回附近的位置,例如:

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 文档,但不知道如何实现它。

我会提供更多示例,但我知道它们都很糟糕。感谢所有建议,谢谢!

【问题讨论】:

    标签: python django tastypie geodjango


    【解决方案1】:

    得到它的工作,这是后代的一个例子:

    在 api.py 中,创建一个如下所示的 Resource:

    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 米内的所有对象。

    【讨论】:

    • 这应该在apply_filters而不是apply_sorting
    最近更新 更多