1

I'm using Django and PostGIS to search users with some distance to a certain point. The abstract code is here:

class User(AbstractUser):
    geo = PointField(null=True, srid=4326)
    objects = GeoManager()

Then run this in shell:

u = User.objects.first()
p = Point(39.9167,116.3833, srid=4326)
u.geo = p
u.save()
User.objects.filter(geo_address__distance_lte=(p, D(km=5)))

But get error like this:

...


/usr/local/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.pyc in geodetic(self, connection)
    170         system that uses non-projected units (e.g., latitude/longitude).
    171         """
--> 172         return self.units_name(connection).lower() in self.geodetic_units
    173
    174     def get_distance(self, value, lookup_type, connection):

/usr/local/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.pyc in units_name(self, connection)
    161     def units_name(self, connection):
    162         if not hasattr(self, '_units_name'):
--> 163             self._get_srid_info(connection)
    164         return self._units_name
    165

/usr/local/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.pyc in _get_srid_info(self, connection)
    147     def _get_srid_info(self, connection):
    148         # Get attributes from `get_srid_info`.
--> 149         self._units, self._units_name, self._spheroid = get_srid_info(self.srid, connection)
    150
    151     def spheroid(self, connection):

/usr/local/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.pyc in get_srid_info(srid, connection)
     35     if srid not in _srid_cache[connection.alias]:
     36         # Use `SpatialRefSys` model to query for spatial reference info.
---> 37         sr = SpatialRefSys.objects.using(connection.alias).get(srid=srid)
     38         units, units_name = sr.units
     39         spheroid = SpatialRefSys.get_spheroid(sr.wkt)

/usr/local/lib/python2.7/site-packages/django/db/models/query.pyc in get(self, *args, **kwargs)
    332             raise self.model.DoesNotExist(
    333                 "%s matching query does not exist." %
--> 334                 self.model._meta.object_name
    335             )
    336         raise self.model.MultipleObjectsReturned(

DoesNotExist: PostGISSpatialRefSys matching query does not exist.
Kane Blueriver
  • 4,170
  • 4
  • 29
  • 48

1 Answers1

1

Finally I found it's because I didn't create my database from an well created spatial db template as I intended to. So to fix this I updated the template db with spatial_ref_sys.sql:

psql -d template_postgis -f /path/to/spatial_ref_sys.sql

Then recreate my db from template_postgis:

createdb my_db -T template_postgis

Everything works now.

Kane Blueriver
  • 4,170
  • 4
  • 29
  • 48