如何根据位置坐标过滤django查询集?

时间:2013-07-16 02:03:23

标签: python django tastypie

假设我有一个照片模型。在照片模型中,我的照片模型中有经度和纬度字段。

 class Photo(models.Model):
      photographer = models.ForeignKey(Photographer, related_name = 'shot_owner')
      title = models.CharField(max_length=140, blank=True)
      description = models.CharField(max_length, blank=True)
      longitude = models.DecimalField(max_digits=16, decimal_places = 14, null=True, blank=True)
      latitude = models.DecimalField(max_digits=16, decimal_places = 14, null=True, blank=True)

我使用Django Tastypie作为我的休息框架。假设用户决定他们想要看到半径10公里范围内的所有照片。怎么能实现这个目标?以下是我的资源:

class PhotosNearMe(ModelResource):
photographer = fields.ForeignKey(PhotographerResource, 'photographer', full=True)
class Meta:
    queryset = Photo.objects.all()
    resource_name = 'photos-near-me'
    fields = ['id', 'title', 'description', 'latitude','longitude','photographer']
    authentication = BasicAuthentication()
    authorization = DjangoAuthorization()
    serializer = Serializer(formats=['json'])
    include_resource_uri = False
    filtering = {
            'photographer' : ALL_WITH_RELATIONS,

}

def get_object_list(self, request):
        return super(PhotosNearMe, self).get_object_list(request).filter(....)

这是我遇到麻烦的地方。正如我之前提到的,用户将能够向我发送他们的坐标,我可以保存它们。类似的东西:

 lati = bundle.obj.latitude
 longi = bundle.obj.longitude

我以后可以使用lat和long来过滤数据库中半径10公里范围内的所有图像。问题是,怎么样?我想过滤某种范围吗?

编辑**

我找到了一些我可以使用的东西,Find items within a certain range of given coordinate

无论如何我可以实现这个吗?

1 个答案:

答案 0 :(得分:5)

如果您要处理大量地理数据,您可以考虑支持spatial lookups的GeoDjango。但是,它仅适用于某些后端,因此如果您的堆栈不符合要求,可能需要更多设置。

否则,另一个选项是做一个小几何并计算你的点周围的边界圆,并对其进行过滤。 Here's an example,看起来有很多关于如何做到这一点的其他文章。

编辑:在回答你关于如何做到这一点的问题时,我假设你的意思是第二部分。我不是TastyPie的专家,但看起来你会看到这个:

  1. 获取用户的lat经度坐标
  2. 计算距离 - 看起来您可以执行此操作natively in SQLor here),但我认为这比最初出现时更复杂。做广场可能更容易,因为这里很容易计算最小值和最大值
  3. 根据最小和最大坐标对get_object_list应用过滤器。
  4. 似乎所有这些都属于ModelResource.build_filters

相关问题