鉴于以下(简化)模型:
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)
objects = models.GeoManager()
忘记将地方的纬度/经度移至PointField()
的那一刻,我试图查看所有Places
并找到最近的城市。目前,我正在做:
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]
这会导致以下错误:
DatabaseError: geometry_distance_spheroid: Operation on two GEOMETRIES with different SRIDs
假设SRID没有默认为4326,我在上面的代码中包含srid=4326
并验证所有城市City.center
的SRID为4326:
In [6]: [c['center'].srid for c in City.objects.all().values('center')]
Out[6]: [4326, 4326, 4326, ...]
关于可能导致这种情况的任何想法?
更新
似乎有一些关于如何创建导致问题的sql查询。抛出错误后,查看sql显示:
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
看起来django正在将point
的{{1}}参数转换为扩展的已知二进制文件。 如果我将distance()
更改为ST_GeomFromEWKB
,一切正常。示例:
ST_GeomFromText
我在文档中找不到有关# 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
如何转换为SQL的内容。我当然可以在查询中使用原始SQL来使事情发挥作用,但我更愿意将所有内容保存在Django框架中。
答案 0 :(得分:0)
我认为这个错误:“在具有不同SRID的两个GEOMETRIES上操作”
数据库上的*****你应该自己改变它