SQLAlchemy Upsert无法找到表“已排除”

问题描述 投票:0回答:1

免责声明:我最近接管了其他人的代码库,因此您在此处看到的一些代码已经预先制作好了。我还将某些变量名称更改为可能实际上不起作用的更通用的代码名称。

我正在尝试使用SQLAlchemy在postgres数据库上批量upsert但是遇到了麻烦。似乎当SQLAlchemy访问数据时,它需要更新表(excluded.columnName)它无法找到。

首先是我得到的错误:

    Missing FROM-clause entry for table "excluded"
    LINE 1: ...tablename) VALUES (excluded.tablename...

我的代码:

    index_fields = list(billocity_db.get_indexes(self.table_name))
    for row in self.data:
        if 'id' in self.column_info.keys():
            del row['id']
        data = row.to_dict()
        insert_stmt = insert(self.table).values(data)
        for i in index_fields:
            if i in data:
                del data[i]
        for key in data.keys():
            data[key] = insert_stmt.excluded[key]
            print(data[key])
        print(data)
        insert_stmt = insert_stmt.on_conflict_do_update(
            #Tried both constraint and index_elements with same result
            #constraint=self.table_name,
            #None of my columns are 'id'. Could that be an issue?
            index_elements=['id'],
            set_=data
        )
        try:
            print(insert_stmt)
            self.session.execute(insert_stmt)
        except Exception as e:
            self.session.rollback()
            self.log.exception(str(e))
        finally:
            self.session.commit()

调用后立即出现错误

self.session.execute(insert_stmt)

这就是insert_stmt在执行之前正确打印的内容,显然column_name和table_name只是占位符。

 INSERT INTO
 table_name (column_name, column_name, column_name, 
 column_name, column_name, column_name, column_name, 
 column_name, column_name, column_name, column_name, 
 column_name, column_name, column_name, column_name, 
 column_name) 
 VALUES
    (
 excluded.column_name, excluded.column_name, excluded.column_name, 
 excluded.column_name, excluded.column_name, excluded.column_name, 
 excluded.column_name, excluded.column_name, excluded.column_name, 
 excluded.column_name, excluded.column_name, excluded.column_name, 
 excluded.column_name, excluded.column_name, excluded.column_name, 
 excluded.column_name
 )
 ON CONFLICT (id) DO 
 UPDATE SET
 column_name= excluded.column_name, column_name= excluded.column_name, 
 column_name= excluded.column_name, column_name= excluded.column_name, 
 column_name= excluded.column_name, column_name= excluded.column_name, 
 column_name= excluded.column_name, column_name= excluded.column_name, 
 column_name= excluded.column_name, column_name= excluded.column_name, 
 column_name= excluded.column_name, column_name= excluded.column_name, 
 column_name= excluded.column_name, column_name= excluded.column_name, 
 column_name= excluded.column_name, column_name= excluded.column_name 
 RETURNING 
 table_name.id

我在网上找不到很多关于这个问题的额外资源,我不知道还有什么可以尝试的。任何帮助,将不胜感激。

python postgresql sqlalchemy upsert
1个回答
0
投票

EXCLUDED可在UPDATE部分找到,但不在VALUES部分。

这是a good tutorial about UPSERT

总是有INSERT ON CONFLICT的官方文档

© www.soinside.com 2019 - 2024. All rights reserved.