Rukomoynikov Rukomoynikov - 11 months ago 72
Python Question

Django sort by distance

i have model:

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

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

Thank, you.

cem cem

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')

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