【发布时间】:2017-06-22 04:06:36
【问题描述】:
我从一个 sqllite 表创建了一个 tmp 表,该表是基于各种选择标准的原始表的子集。示例在屏幕截图中。
我正在尝试一次循环遍历表记录,以便更新每个记录中的字段。我遇到了Mapper could not assemble any primary key columns 中详述的问题。基于http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key 的建议。基于这个讨论,我确实有一个候选键,它是一个唯一的 id:列“id”。因此,我将代码更改为:
source_table= self.source
engine = create_engine(db_path)
Base = declarative_base()
# metadata = Base.metadata
# Look up the existing tables from database
Base.metadata.reflect(engine)
# Create class that maps via ORM to the database table
table = type(source_table, (Base,), {'__tablename__': source_table}, __mapper_args__ = {
'primary_key':'id'
})
Session = sessionmaker(bind=engine)
session = Session()
i = 0
for row in session.query(table).limit(500):
i += 1
print object_as_dict(row)
但这给出了:
TypeError: type() takes 1 or 3 arguments
如何使用 mapper_args 参数将 id 标识为主键
编辑:
我试过了:
table = type(source_table, (Base,), {'__tablename__': source_table}, {"__mapper_args__": {"primary_key": [Base.metadata.tables[source_table].c.id]}})
给予:
TypeError: type() takes 1 or 3 arguments
【问题讨论】:
标签: python sqlalchemy