Given the following (simplified) models:
from django.contrib.gis.db import models
class City(models.Model):
center = models.PointField(spatial_index=True, null=True)
objects = models.GeoManager()
class Place(models.Model):
city = models.ForeignKey(City, null=True)
lat = models.FloatField(null=True)
lng = models.FloatField(null=True)
开发者_JAVA百科 objects = models.GeoManager()
Forgetting for the moment that the lat/lng in Place should be moved to a PointField()
, I am trying to look through all of the Places
and find the closest city. Currently, I am doing:
from django.contrib.gis.geos import Point
places = Property.objects.filter(lat__isnull=False, lng__isnull=False)
for place in places:
point = Point(place.lng, place.lat, srid=4326) # setting srid just to be safe
closest_city = City.objects.distance(point).order_by('distance')[0]
This results in the following error:
DatabaseError: geometry_distance_spheroid: Operation on two GEOMETRIES with different SRIDs
Assuming that the SRIDs were not defaulting to 4326, I included srid=4326
in the above code and verified that all of the cities have City.center
has an SRID of 4326:
In [6]: [c['center'].srid for c in City.objects.all().values('center')]
Out[6]: [4326, 4326, 4326, ...]
Any ideas on what could be causing this?
UPDATE:
There seems to be something in how the sql query is created that causes a problem. After the error is thrown, looking at the sql shows:
In [9]: from django.db import connection
In [10]: print connection.queries[-1]['sql']
SELECT (ST_distance_sphere("model_city"."center",
ST_GeomFromEWKB(E'\\001\\001...\\267C@'::bytea))) AS "distance",
"model_city"."id", "model_city"."name", "listing_city"."center"
FROM "model_city" ORDER BY "model_city"."name" ASC LIMIT 21
It looks like django is turning the point
argument of distance()
into Extended Well-Known Binary. If I then change ST_GeomFromEWKB
to ST_GeomFromText
everything works fine. Example:
# SELECT (ST_distance_sphere("listing_city"."center",
ST_GeomFromText('POINT(-118 38)',4326))) AS "distance",
"model_city"."name", "model_city"."center" FROM "model_city"
ORDER BY "listing_city"."name" ASC LIMIT 5;
distance | name | center
------------------+-------------+----------------------------------------------------
3124059.73265751 | Akron | 0101000020E6100000795DBF60376154C01CB62DCA6C8A4440
3742978.5514446 | Albany | 0101000020E6100000130CE71A667052C038876BB587534540
1063596.35270877 | Albuquerque | 0101000020E6100000CC0D863AACA95AC036E7E099D08A4140
I can't find anything in the documentation that speaks to how GeoQuerySet.distance()
translates into SQL. I can certainly use raw SQL in the query to get things to work, but would prefer to keep everything nicely in the Django framework.
i think this error : "Operation on two GEOMETRIES with different SRIDs"
"geometry_columns" table on your database is set different srid between your table name to process
***** you should change it yourself
精彩评论