【问题标题】:Point type in sqlalchemy?sqlalchemy中的点类型?
【发布时间】:2016-09-11 00:21:39
【问题描述】:

我在 Postgres 中发现了有关 Point 类型的信息:http://www.postgresql.org/docs/current/interactive/datatype-geometric.html

有这个的 SQLAlchemy 版本吗?

我以这种方式存储值:(40.721959482, -73.878993913)

【问题讨论】:

    标签: python postgresql flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

    您可以使用geoalchemy2,这是 sqlalchemy 的扩展,也可以与 flask-sqlalchemy 一起使用。

    from sqlalchemy import Column
    from geoalchemy2 import Geometry
    # and import others
    
    class Shop(db.Model):
        # other fields
        coordinates = Column(Geometry('POINT'))
    

    【讨论】:

    • 在 Posgresql 中,数据类型是点,还是几何(点)?如果我在创建表时将列位置设置为点数据类型(位置点),我可以毫无问题地加载到我的 csv 文件中。当我尝试加载 csv 时执行 Location geometry(Point)(我正在查看 PostGIS 文档)时出现错误:Database error XX000: parse error - invalid geometry HINT: "(4" <-- parse error at position 2 within geometry CONTEXT: COPY crime_data_nyc, line 1, column location: "(40.6227027620001" CSV file has the Location column data as "(40.8037530600001, -73.955861904)"
    • 修改最后一条评论:在执行location = db.Column(Geometry(geometry_type='POINT') 时将postgresql 中的位置数据类型指向ProgrammingError: (psycopg2.ProgrammingError) function st_asewkb(point) does not exist [...] HINT: No function matches the given name and argument types. You might need to add explicit type casts. 所以我认为这是需要发生的:创建表中的Postgresql 创建位置列为:CREATE TABLE Blah( Location geometry(Point));在地球炼金术中,类型为location = db.Column(Geometry(geometry_type='POINT'))
    【解决方案2】:

    你可以扩展UserDefinedType来实现你想要的。

    Here's an example I found 非常接近您想要的子类化 UserDefinedType

    请注意,Mohammad Amin's answer 仅在您的点旨在成为地理点(经纬度限制)时才有效。如果您想表示平面上的任何点,则不适用。此外,在这种情况下,您需要安装 PostGIS 扩展程序,如果您使用地理点,我鼓励您安装它,因为它提供了许多实用程序和额外功能。

    【讨论】:

    • 如果您不想添加 PostGIS 扩展,这是最接近正确答案的方法。唯一的问题是该示例并非专门针对 Point 类型
    【解决方案3】:

    我发现这是对 Mohammad 答案的轻微修改。

    是的,我需要通过 geo/sqlalchemy 添加一个点列

    from sqlalchemy import Column
    from geoalchemy2 import Geometry
    # and import others
    
    class Shop(db.Model):
        # other fields
        coordinates = Column(Geometry('POINT'))
    

    在我的 PostGIS/Gres 和 PGloader 方面,因为我从 csv 加载,该 csv 将我的纬度和经度点格式化为:"(40.721959482, -73.878993913)" 我需要在 vim 中为我的所有条目做一个宏(有很多)为了强制该列遵循在 PostGIS 中创建点的方式,所以我将 csv 列转换为point(40.721959482 -73.878993913),然后在创建表时将数据类型设置为几何(点)location geometry(point) 的位置列。

    【讨论】:

    • 澄清:仅当您启用了 PostGIS 扩展时才适用。 SQLAlchemy 或 GeoAlchemy2 似乎不支持没有扩展名的 Posgres 中的 Point 类型
    • AArias 下面的回答应该被接受,因为这需要一个额外的库,可能会使你的代码库膨胀
    • 我可以在 Alembic 迁移中使用 Geometry 类,还是需要为迁移编写自定义 SQL?例如,我可以这样做:op.create_table('gps', sa.Column('coordinates', Geometry('POINT'), nullable=False), ...)
    猜你喜欢
    • 2014-03-10
    • 1970-01-01
    • 2020-11-12
    • 2020-11-06
    • 2011-09-28
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多