簡體   English   中英

不能將Postgres的ARRAY與SQLAlchemy一起使用

[英]Cannot use Postgres's ARRAY with SQLAlchemy

我不能通過SQLAlchemy使用以下代碼向Postgre添加2D整數數組:

    def create_polygon(x, y, w, h):
        polygon = []
        polygon.append([1, 2])
        return polygon


    engine = create_engine('postgresql://usr:pwd@localhost:5432/db', echo=True)
    meta = MetaData()

    table = Table(
        'table', meta,
        Column('id', Integer, primary_key=True), 
        Column('polygon', ARRAY(Integer, dimensions=2))
    )
    meta.create_all(engine)

    conn = engine.connect()

    for line in lines:            
        insert = zone_by_cam.insert(
            polygon = create_polygon(*line.params)
        )

        conn.execute(insert)

我收到此錯誤消息:

Additional arguments should be named <dialectname>_<argument>, got 'polygon'

然后,我將polygon的名稱更改為postgresql_polygon (在文檔中找不到該位置),並改為使用它:

Argument 'postgresql_polygon' is not accepted by dialect 'postgresql' on behalf of <class 'sqlalchemy.sql.dml.Insert'>

我怎樣才能解決這個問題? 謝謝!

Table.insert()不接受要作為關鍵字參數插入的值,並將它不處理的任何關鍵字參數傳遞給Insert的方言特定實現。 錯誤然后告訴您,實現希望這些參數遵循<dialectname>_<argument>格式,但是您給了它polygon postgresql_polygon不是在PostgreSQL的方言文檔 ,因為沒有這樣的說法存在。 初始修正是簡單,將值作為一dict中的關鍵字參數values ,或使用Insert.values()

for line in lines:            
    insert = zone_by_cam.insert().values(
        polygon=create_polygon(*line.params)
    )

    conn.execute(insert)

除了單獨的插入,您還可以在單​​個executemany操作中傳遞所有“多邊形”:

insert = zone_by_cam.insert().values([
    {'polygon': create_polygon(*line.params)} for line in lines
])

conn.execute(insert)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM