【问题标题】:Upserting with SQLAlchemy into Postgres to Table with a '.' in the name使用 '.' 将 SQLAlchemy 更新到 Postgres 到表中在名字里
【发布时间】:2021-05-19 07:08:44
【问题描述】:

我正在尝试将其插入到 postgres 表中,其中某些列具有“。”以他们的名义。 列名示例:country.name。 最好不要更改列名。

当我尝试这样做时,我得到一个错误。

def upsert(df: DataFrame, engine: sql_engine) -> None:
  with engine.connect() as conn:
    base = automap_base()
    base.prepare(engine, reflect=True, schema="some_schema")
    table1= Table('table1', base.metadata,
                      autoload=True, autoload_with=engine, schema="some_schema")
    stmt = insert(table1).values(df.to_dict('records'))
    conn.execute(stmt.on_conflict_do_update(
        constraint='table1_pkey',
        set_=dict(country.name=stmt.excluded.country.name
                  )))

我收到以下错误:

SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

我一直在尝试遵循这个在列名出现“。”之前运行良好的食谱。 https://docs.sqlalchemy.org/en/14/dialects/postgresql.html#updating-using-the-excluded-insert-values

有什么建议吗?

【问题讨论】:

    标签: python postgresql sqlalchemy upsert


    【解决方案1】:

    sqlalchemy 语句包含一个排除字段,所有列都在其中,如果您使用它,那么它将起作用。 我创建了一个“updated_dict”,其中所有列名和对象都来自排除的列。我过滤掉主键。 这样,如何构造列的名称就无关紧要了。

    def upsert(df: DataFrame, engine: sql_engine) -> None:
      with engine.connect() as conn:
        base = automap_base()
        base.prepare(engine, reflect=True, schema="some_schema")
        table1= Table('table1', base.metadata,
                          autoload=True, autoload_with=engine, schema="some_schema")
        stmt = insert(table1).values(df.to_dict('records'))
    
        update_dict = {
            c.name: c
            for c in stmt.excluded
            if not c.primary_key
            }
    
        conn.execute(stmt.on_conflict_do_update(
            constraint='table1_pkey',
            set_=update_dict ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 2023-01-29
      • 2022-01-11
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多