Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort by latitude in geodjango

I have the following model:

class Stop(models.Model):
    name = models.CharField(max_length=50)
    point = models.PointField()
    objects = models.GeoManager()

I want to sort my stops from north to south. How do I do this? Stop.objects.order_by('point') sorts them west to east.

thanks.

This is my full model:

from django.contrib.gis.db import models
from django.core.urlresolvers import reverse

class Stop(models.Model):
    gtfs_stop_id = models.IntegerField(db_index=True, unique=True)
    name = models.CharField(max_length=50)
    point = models.PointField()
    parkings = models.GeometryCollectionField(null=True, blank=True)
    objects = models.GeoManager()

    def get_absolute_url(self):
        return reverse('core:stop', args=(self.id,))

    def __str__(self):
        return self.name
like image 653
eran Avatar asked May 22 '16 22:05

eran


1 Answers

Since your point field is Geometry and not geography you are in luck.

from django.db.models import F, Func
Stop.objects.annotate(lat=Func('point',function='ST_X')).order_by('lat')

I am using ST_X here instead of ST_Y because PostGIS the best of the geodjango databases the convention is to store lng,lat

If you your point field had been geography the above function call will not have worked because ST_X and ST_Y are only available on geometry fields. Geography fields need to be cast to Geometry before you can use these functions.

like image 81
e4c5 Avatar answered Nov 15 '22 21:11

e4c5