在 geodjango 中上传形状文件

发布于 2025-01-16 17:11:04 字数 1324 浏览 3 评论 0原文

我正在尝试通过 django 和 geopandas 将形状文件上传到 postgres。但它返回此错误:

(psycopg2.errors.DuplicateTable) relation "idx_Village_kcnT1Uu_geom" already exists

这是我的模型:

class ShapeFile(models.Model):
    name = models.CharField(max_length=45)
    description = models.TextField()
    file = models.FileField(upload_to='user_shape_file')
    date = models.DateTimeField(auto_now_add=True)

并且我正在使用此信号上传它:

@receiver(post_save, sender=ShapeFile)
def post_save_r(instance, **kwargs):
    file = instance.file.path
    file_format = os.path.basename(file).split('.')[-1]
    file_name = os.path.basename(file).split('.')[0]
    file_path = os.path.dirname(file)
    name = instance.name
    connection = 'postgresql://postgres:1234@localhost:5432/geoapp'
    with zipfile.ZipFile(file, 'r') as opened_zip:
        opened_zip.extractall(file_path)
    shape_file = glob.glob(r'{}/**/*.shp'.format(file_path), recursive=True)[0]
    gfr = gpd.read_file(shape_file)
    epsg = 4326
    engine_ = create_engine(connection)
    gfr['geom'] = gfr['geometry'].apply(lambda x: WKTElement(x.wkt, srid=epsg))
    gfr.to_sql(name, engine_, 'public', if_exists='replace', index=False,
           dtype={'geom': Geometry('Geometry', srid=epsg)})

但它返回此错误:

i am Trying to upload a shape file to postgres by django and geopandas. but it return this error:

(psycopg2.errors.DuplicateTable) relation "idx_Village_kcnT1Uu_geom" already exists

this is my model:

class ShapeFile(models.Model):
    name = models.CharField(max_length=45)
    description = models.TextField()
    file = models.FileField(upload_to='user_shape_file')
    date = models.DateTimeField(auto_now_add=True)

and i am using this signal to upload it:

@receiver(post_save, sender=ShapeFile)
def post_save_r(instance, **kwargs):
    file = instance.file.path
    file_format = os.path.basename(file).split('.')[-1]
    file_name = os.path.basename(file).split('.')[0]
    file_path = os.path.dirname(file)
    name = instance.name
    connection = 'postgresql://postgres:1234@localhost:5432/geoapp'
    with zipfile.ZipFile(file, 'r') as opened_zip:
        opened_zip.extractall(file_path)
    shape_file = glob.glob(r'{}/**/*.shp'.format(file_path), recursive=True)[0]
    gfr = gpd.read_file(shape_file)
    epsg = 4326
    engine_ = create_engine(connection)
    gfr['geom'] = gfr['geometry'].apply(lambda x: WKTElement(x.wkt, srid=epsg))
    gfr.to_sql(name, engine_, 'public', if_exists='replace', index=False,
           dtype={'geom': Geometry('Geometry', srid=epsg)})

but it return this error:

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文