You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在SQLModel创建的模型中使用PostGIS几何类型?若可行该如何操作?

可以在SQLModel中使用PostGIS几何类型,具体实现步骤如下

1. 安装依赖

SQLModel本身不直接支持PostGIS,需要结合GeoAlchemy2处理几何类型,同时安装PostgreSQL的Python驱动:

pip install sqlmodel geoalchemy2 psycopg2-binary

2. 创建包含PostGIS类型的数据模型

利用GeoAlchemy2提供的Geometry类型直接定义SQLModel的字段,指定几何类型(如POINT、POLYGON)和空间参考系(常用4326代表WGS84经纬度)。以下是完整示例:

from sqlmodel import SQLModel, Field, Session, create_engine
from geoalchemy2 import Geometry
from geoalchemy2.functions import ST_MakePoint, ST_DWithin


class Place(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    # 定义WGS84坐标系的Point类型字段
    location: Geometry = Field(sa_column=Geometry(geometry_type="POINT", srid=4326))


# 替换为你的数据库连接信息
DATABASE_URL = "postgresql://username:password@localhost/your_db"
engine = create_engine(DATABASE_URL, echo=True)

# 初始化数据库:启用PostGIS扩展并创建表
def init_db():
    with engine.begin() as conn:
        conn.execute("CREATE EXTENSION IF NOT EXISTS postgis;")
        SQLModel.metadata.create_all(conn)

if __name__ == "__main__":
    init_db()

    # 插入带点位的数据
    with Session(engine) as session:
        new_place = Place(
            name="Central Park",
            location=ST_MakePoint(-73.968285, 40.785091)
        )
        session.add(new_place)
        session.commit()

    # 空间查询:查找目标点10公里内的地点
    with Session(engine) as session:
        target_point = ST_MakePoint(-73.97, 40.78)
        results = session.exec(
            Place.__table__.select().where(
                ST_DWithin(Place.location, target_point, 10000)
            )
        ).all()
        print([place.name for place in results])

关键注意事项

  • 确保PostgreSQL数据库已安装并启用PostGIS扩展(首次使用需执行CREATE EXTENSION postgis;)
  • 定义几何字段时,必须明确geometry_type和srid,避免类型不匹配
  • 使用PostGIS空间函数时,直接导入geoalchemy2.functions中的对应函数即可,SQLModel会自动兼容SQLAlchemy语法

内容的提问来源于stack exchange,提问作者Charalamm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:35:20