使用sqlalchemy插入postgres数据库时忽略未使用的列

ignoring unconsumed columns while inserting into postgres database using sqlalchemy

我想将 python 词典中的数据插入到 table 中。但是我的字典包含的键比 table 中的列多。所以我在插入时收到错误 sqlalchemy.exc.CompileError: Unconsumed column names: column_name。我只想插入存在于 table 中的列名并忽略额外的列。

如何使用 sqlalchemy 做到这一点?

我使用的代码是

from sqlalchemy import *
from sqlalchemy.dialects import postgresql

db = create_engine('postgresql+psycopg2://localhost:5432/postgres')
meta = MetaData()
meta.bind = db

data = [{
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4,
    'e': 5,
    'f': 6
}]

ins_stmt = postgresql.insert(table_object).values(data)
db.execute(ins_stmt)

我的 table_object 包含列 a、b、c、d、e。

P.S.- 我正在使用 sqlalchemy 1.4

我不知道有什么方法可以让 insert 丢弃多余的项目,因此必须事先过滤掉它们。您可以通过将 table 的列名与字典的键进行比较来做到这一点。

column_names = {c.name for c in table_object.columns}
fixed = [{k: v for k, v in d.items() if k in (d.keys() & column_names)} for d in data]

ins_stmt = postgresql.insert(table_object).values(fixed)
with engine.connect() as conn:
    with conn.begin():
        conn.execute(ins_stmt)