本文介绍了从经度/纬度迁移到GeoDjango点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django ORM,Postgres/PostGIS和Django迁移,如何将现有的longitudelatitude float字段转换为单个GeoDjango Point字段?

Using the Django ORM, Postgres/PostGIS, and Django migrations, how do I convert my existing longitude and latitude float fields into a single GeoDjango Point field?

我正在寻找类似Location.objects.update(point=(F('longitude'), F('latitude')))的东西.

I was looking for something like Location.objects.update(point=(F('longitude'), F('latitude'))).

推荐答案

假设您有一个PointPoint之类的对象

assuming you have an object with a PointField like

from django.contrib.gis.db import models

class Location(models.Model):
    longitude = models.FloatField()
    latitude = models.FloatField()
    point = models.PointField(geography=True, default='POINT(0.0 0.0)') #or similar

您可以这样做:

from django.contrib.gis.geos import Point

for l in Location.objects.all():
    l.point = Point(x=l.longitude, y=l.latitude, srid=4326)
    l.save()

或者如果您真的想进行一次更新(不过未经测试),则可以使用以下一条语句:

or this single statement should work if you really want a single update (untested though):

Location.objects.all().update(point=Point(x=F('longitude'), y=F('latitude'), srid=4326))

注意:尽管我已经使用了GeoDjango和postgis了很多,但我绝不是专家.我不知道PointField的功能是什么...如果它正在创建关系,那么它将无法在单个语句中工作,因为Django不允许在update语句中的表之间进行更新,因此,您必须进行遍历,如果只是格式化数据然后应该可以正常工作...我做了一点研究,似乎srid是唯一的关系,所以应该没问题,因为在更新语句中创建静态关系就可以了.

NOTE: though I've used GeoDjango and postgis quite a bit, I'm by no means an expert in it. I don't know what the PointField does under the hood... if it's creating a relationship then it will not work in a single statement as Django doesn't allow updating across tables in update statements, you must loop over, if it's just formatting the data then it should work fine... I did a little research and it seems like the srid is the only relationship, so this should be fine because creating static relationships IS fine in an update statement.

从上面发布的答案中提取出来,您可以简单地将其作为一个函数(例如,名为set_points)写入迁移文件中,然后将其添加到迁移的操作"部分中以运行它:

drawing from the answer you posted above, you would simply write that as a function (named set_points for instance) in your migration file and then add this in the operations section of your migration to run it:

migrations.RunPython(set_points),

移民写作参考书:

https://docs.djangoproject.com/en/2.0/howto/writing-migrations/

这篇关于从经度/纬度迁移到GeoDjango点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:15