Update a PostgreSQL array using SQLAlchemy

前端 未结 1 1641
广开言路
广开言路 2021-02-13 21:55

I\'m trying to update an integer array on a PostgreSQL table using a SQL statement in SQLAlchemy Core. I first tried using the query generator, but couldn\'t figure out how to d

相关标签:
1条回答
  • 2021-02-13 22:52

    If your table is defined like this:

    from datetime import datetime
    from sqlalchemy import *
    from sqlalchemy.dialects.postgresql import ARRAY
    
    meta = MetaData()
    surveys_table = Table('surveys', meta,
        Column('surveys_id', Integer, primary_key=True),
        Column('questions_ids_ordered', ARRAY(Integer)),
        Column('created_at', DateTime, nullable=False, default=datetime.utcnow)
    )
    

    Then you can simply update your array in the following way (works with psycopg2):

    engine = create_engine('postgresql://localhost')
    conn = engine.connect()
    u = surveys_table.update().where(surveys_table.c.id == 46).\
         values(questions_ids_ordered=[237, 238, 239, 240, 241, 242, 243])
    conn.execute(u)
    conn.close()
    

    Or, if you prefer, write raw SQL using text() construct:

    from sqlalchemy.sql import text
    with engine.connect() as conn:
        u = text('UPDATE surveys SET questions_ids_ordered = :q WHERE id = :id')
        conn.execute(u, q=[237, 238, 239, 240, 241, 242, 243], id=46)
    
    0 讨论(0)
提交回复
热议问题