gpt4 book ai didi

django - GeoDjango 从 json 或点保存数据

转载 作者:行者123 更新时间:2023-12-02 11:56:02 24 4
gpt4 key购买 nike

如果我已经在文件(作为列表)或内存中或以 json 格式存在现有的 MultiString 坐标,如何重写保存函数来保存这些点,而不是用户在 map 上创建对象?或者更准确地说,我如何将这些点加载到模型和数据库中?

内存/文件中的坐标

[[36.66678428649903, -1.5474249907643578], [36.670904159545906, -1.542620219636788], [36.66635513305665,-1.5353272427374922],[36.662406921386726, -1.5403894293513378]]

模型.py

class LogsUpload(models.Model):
name = models.CharField(max_length=240)
geom = gis_models.MultiLineStringField(blank=True, null=True)

如何使用坐标并将其保存在 geom 字段中?

最佳答案

使用 GEOS API 中的 LineStringMultiLineString 类在内存中创建线和多线,并将它们分配给模型的字段:

>>> from django.contrib.gis.geos import LineString, MultiLineString
>>> DATA = [[36.66678428649903, -1.5474249907643578], [36.670904159545906, -1.542620219636788], [36.66635513305665,-1.5353272427374922],[36.662406921386726, -1.5403894293513378]]
>>> line = LineString(DATA)
>>> line
<LineString object at 0x7f96538f49a0>
>>> line.length
0.02134446840090856
>>> line.geojson
'{ "type": "LineString", "coordinates": [ [ 36.666784286499031, -1.547424990764358 ], [ 36.670904159545906, -1.542620219636788 ], [ 36.666355133056648, -1.535327242737492 ], [ 36.662406921386726, -1.540389429351338 ] ] }'
>>> multi_line = MultiLineString(line)
>>> multi_line
<MultiLineString object at 0x7f96536ccbc0>
>>> multi_line[0]
<LineString object at 0x7f964187b3c8>
>>> multi_line.length
0.02134446840090856
>>> multi_line.geojson
'{ "type": "MultiLineString", "coordinates": [ [ [ 36.666784286499031, -1.547424990764358 ], [ 36.670904159545906, -1.542620219636788 ], [ 36.666355133056648, -1.535327242737492 ], [ 36.662406921386726, -1.540389429351338 ] ] ] }'

>>> from myapp.models import LogsUpload
>>> o = LogsUpload(name="foo", geom=multi_line)
>>> o.full_clean()
>>> o.save()

使用 Django 2.0 和 PostGIS 进行测试。

关于django - GeoDjango 从 json 或点保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48165329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com