为django添加对postgresql地球距离扩展的支持
django-earthdistance的Python项目详细描述
对于django使用postgresql的地球距离扩展>;=1.8(对于较旧的版本,请参见,并使用djorm表达式分支)
EarthDistance允许在不使用Postgis的情况下进行快速地理本地化查询
使用python 2.7和3.3进行了测试
用法
必须在postgresql bd中启用立方体和地球距离扩展,因此请登录 数据库使用pgsql并安装扩展:
=>createextensioncube;=>createextensionearthdistance;
按半径r的圆形不一致性内的行筛选
fromdjango.dbimportmodelsfromdjango_earthdistance.modelsimportEarthDistanceQuerySetclassMyModel(models.Model):latitute=models.FloatField()longitude=models.FloatField()objects=EarthDistanceQuerySet.as_manager()# Define fields to query in DistanceExpression initialization# search with lat=0.2546 and lon=-38.25 and distance 1500 meters# use param `annotate` to set a custom field for the distance, `_ed_distance` as defaultMyModel.objects.in_distance(1500,fields=['latitude','longitude'],points=[0.2546,-38.25])
用两点之间的距离注释查询返回的每一行
fromdjango_earthdistance.modelsimportEarthDistance,LlToEarthMyModel.objects.filter(....).annotate(distance=EarthDistance([LlToEarth([0.2546,-38.25]),LlToEarth(['latitude','longitude'])]))
使用索引优化性能
postgresql允许在函数结果中使用gist索引,一个很好的性能改进是在 一个指数,ll_to_earth是一个计算地球表面某一点位置的函数(假设地球是 完美球形)
-- Example MyModel table is app_mymodel and points columns are latitude and longitude CREATEINDEXmymodel_locationONapp_mymodelUSINGgist(ll_to_earth(latitude,longitude));
对于django<;1.7
另外,最好使用south,只需将此迁移添加到migrations/文件夹并根据需要进行编辑,就会创建索引
classMigration(SchemaMigration):defforwards(self,orm):cursor=connection.cursor()cursor.execute("CREATE INDEX mymodel_location ON app_mymodel USING gist (ll_to_earth(latitude, longitude));")defbackwards(self,orm):# Deleting field 'Venue.coords'cursor=connection.cursor()cursor.execute("DROP INDEX mymodel_location ON app_mymodel;")