Django按距离排序 [英] Django sort by distance

查看:430
本文介绍了Django按距离排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有模型:

class Vacancy(models.Model):
    lat = models.FloatField('Latitude', blank = True)
    lng = models.FloatField('Longitude', blank = True)


$ b $我应该按照距离(距离是无穷远)进行查询排序吗?工作在PosgreSQL,GeoDjango如果需要。

Hi should i make query to sort by distance (distance is infinity) ? Working on PosgreSQL, GeoDjango if it required.

谢谢你。

推荐答案

首先,最好做一个点字段,而不是使用lat和lnt分离:

First of all, it is better to make a point field instead of making lat and lnt separated:

    from django.contrib.gis.db import models

    location = models.PointField(null=False, blank=False, srid=4326, verbose_name="Location")

然后,您可以像下列那样进行过滤:

Then, you can filter it like that:

    from django.contrib.gis.geos import *
    from django.contrib.gis.measure import D

    distance = 2000 
    ref_location = Point(1.232433, 1.2323232)

    res = yourmodel.objects.filter(location__distance_lte=(ref_location, D(m=distance))).distance(ref_location).order_by('distance')

在stackoverlow中已经有几个问题,如果你检查它们就更好。

There are already several questions like that in stackoverlow, better if you'd check them.

这篇关于Django按距离排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆