为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;")

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java通过Spring MVC web应用程序向客户端发送文本文件   java是否可以在运行时动态实例化DAO类?   调用VB。来自Java的net函数   java在Android中通过单击打开特定文件夹   java如何使用maven pom。xml标识非标准项目结构中的testng测试用例?   java为什么FOP在大文件上崩溃?   Architecture python+flask和spring boot+java   java Kafka工具根本没有启动Ubuntu 19.10   如何使用Eclipse运行Java USB API for Windows   java如何在Eclipse中查看J2EE预览服务器/容器的日志/控制台?   网页抓取是否可以使用Java crawler crawler4j暂停和恢复抓取?   java当我第二次按下按钮时,应用程序停止工作   带有偏移量和限制的java SQLite分页问题   java如何在OSX mavericks中将端口80转发到8080   java从泛型方法调用非泛型方法   java My代码未按预期工作。十进制输出不是它应该的样子   节点。java中的js加密(jasypt)和nodejs中的解密   java乘法表不工作数组索引超出范围   java将JDBC与Firebirdsql连接起来