python - alembic 并获取最后插入的值

标签 python sqlalchemy alembic

我正在使用 alembic 来管理我的数据库结构。

在使用 id 作为整数和主键添加表后,id 列将是一个自动增量列。我如何查询升级脚本中的数据,以确保获得正确的 ID(我知道在这种特定情况下它是 1)?

我知道怎么做

#creating the table
op.create_table(
    'srv_feed_return_type',
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('name', sa.String(50), nullable=False),
    sa.Column('created', sa.DateTime, server_default=func.now(), nullable=False),
    sa.Column('created_by', sa.String(50), nullable=False),
    sa.Column('last_updated', sa.DateTime, nullable=False),
    sa.Column('last_updated_by', sa.String(50), nullable=False)
)

#table for operations
srv_feed_return_type = table('srv_feed_return_type',
                             column('name'),
                             column('created'),
                             column('created_by'),
                             column('last_updated'),
                             column('last_updated_by'))

#bulk insert
op.bulk_insert(srv_feed_return_type,
               [
                   {'name': 'dataset',
                    'created': datetime.now(), 'created_by': 'Asken',
                    'last_updated': datetime.now(), 'last_updated_by': 'Asken'}
               ])

我知道我可以进行更新,但我如何使用类似下面的内容进行选择?

op.execute(
    srv_feed_return_type.update().\
        where(srv_feed_return_type.c.name==op.inline_literal('dataset')).\
        values({'name':op.inline_literal('somethingelse')})
        )

最佳答案

首先要拥有自动增量列,您需要修改表模式定义以为主键列传递序列:sa.Column('id', sa.Integer, Sequence('srv_feed_r_t_seq'), primary_key=True),

#creating the table
op.create_table(
    'srv_feed_return_type',
    sa.Column('id', sa.Integer, Sequence('srv_feed_r_t_seq'),primary_key=True),
    sa.Column('name', sa.String(50), nullable=False),
    sa.Column('created', sa.DateTime, server_default=func.now(), nullable=False),
    sa.Column('created_by', sa.String(50), nullable=False),
    sa.Column('last_updated', sa.DateTime, nullable=False),
    sa.Column('last_updated_by', sa.String(50), nullable=False)
)

现在关于如何获取PK id:

op.executeop.bulk_insert 不会返回任何结果。但是您可以获得用于这些操作的相同连接。

在执行bulk_insertexecute(table.update ...) 后,您可以在同一上下文中运行选择查询并检索感兴趣记录的 PK id:

connection = op.get_bind()
r = connection.execute(srv_feed_return_type.select().where(...))
for row in r:
    pk_id = r['id']
    """or something more sophisticated"""

您需要在 where 子句中指定适当的过滤器,以确保您以唯一的方式识别最近更改的记录。

这里是 some example of similar functionality , 但它有硬编码的选择查询

关于python - alembic 并获取最后插入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15543613/

相关文章:

python - 如何将 pandas Dataframe 与列表匹配并合并?

python - Sql-alchemy 完整性错误

python - 用于添加索引的 SQLAlchemy/Alembic 原始 SQL

python - 从不同子文件夹的子文件夹相对导入 python 模块

python - sqlalchemy 中的并发

python - 使用 alembic 对 flask_sqlalchemy 中新添加的不可空列进行迁移时出现 "ALTER"语法错误

python Tkinter 将文本显示为超链接

python - 保存 matplotlib 图形的特定部分

python - 如何执行程序或调用系统命令?

python - SqlAlchemy - 按关系属性过滤