Django Rest Framework - 如何限制使用 Geolocation 返回的结果?

Django Rest Framework - How do I limit results returned with Geolocation?

我有一个存储用户位置的模型:

[
{
    "url": "http://192.168.0.22:8000/status/1/",
    "id": 1,
    "owner": 1,
    "test_info": "",
    "created_at": "2015-05-02T07:09:16.535689Z",
    "updated_at": "2015-05-02T07:09:16.535746Z",
    "geolocation": null,
    "jukebox_mode_enabled": false
},
{
    "url": "http://192.168.0.22:8000/status/2/",
    "id": 2,
    "owner": 2,
    "test_info": "",
    "created_at": "2015-05-02T07:09:24.206959Z",
    "updated_at": "2015-05-02T07:09:24.207042Z",
    "geolocation": null,
    "jukebox_mode_enabled": false
},

我正在尝试实现一个允许用户查询并查看附近还有谁的系统,但出于安全原因,我想将结果限制为 1KM 的用户。

实现此目标的最佳方法是什么?

P.S - "status" 使用 oneToOneField 绑定到 django 模型中的普通用户模型。

您正在寻找的是 query/filter 通过地理定位的能力。看看GeoDjango.

一旦您可以 运行 具有地理范围的模型 filter(),那么只需使用 django-rest-framework 将其应用到您的 APIView 即可。

两件事,您应该使用 Django's GIS (GeoDjango) features and the GIS plugin Django REST 框架。

GeoDjango 将在本地与您的数据库一起工作(可能 PostGIS) to accurately store and represent the geospatial data. This means you won't have to worry about normalizing locations as they are given to you, and you won't have to manually handle filtering - like finding locations in a radius

GIS 插件提供的 a DistanceToPoint filter 听起来正是您要找的东西。您可以将米数连同用作中心的点一起传递,它将删除落在该范围之外的所有结果。这将允许您使用 Django REST 框架的内置视图和序列化程序,而无需处理查询集并自行应用过滤。