【问题标题】:Creating a primary key in sqlalchemy when creating a table instance创建表实例时在sqlalchemy中创建主键
【发布时间】: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

如何使用 ma​​pper_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


    【解决方案1】:

    __mapper_args__ 需要是在类上定义的属性。而你需要写

    class Foo(Base):
        ...
        __mapper_args__ = {...}
    

    使用class语法定义类时,需要写

    type("Foo", (Base,), {..., "__mapper_args__": {...}})
    

    使用type 函数定义类时。

    注意__mapper_args__ 可能需要

    {"primary_key": [Base.metadata.tables[source_table].c.id]}
    

    而不是

    {"primary_key": "id"}
    

    让它正常工作。

    【讨论】:

    • 谢谢,我快到了,但您介意检查一下编辑吗?
    • @user61629 type 接受三个参数。你给它四个。它必须是type(source_table, (Base,), {"__tablename__": source_table, "__mapper_args__": ...})
    • 最终答案:-> table = type(source_table, (Base,), {"tablename": source_table, "mapper_args": { "primary_key":[Base.metadata.tables[source_table].c.id]}})
    猜你喜欢
    • 2010-11-23
    • 2014-11-09
    • 2016-08-13
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2014-07-09
    相关资源
    最近更新 更多