如何使用Alembic/SQLAlchemy将表对象实例化为bulk_insert行 [英] How to instantiate a table object to bulk_insert rows using alembic / SQLAlchemy

查看:68
本文介绍了如何使用Alembic/SQLAlchemy将表对象实例化为bulk_insert行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 bulk_insert 将数据插入到Postgres数据库中的现有表( services )中.如何实例化此表对象,以便可以对其进行bulk_insert?

I am trying to use bulk_insert to insert data into an existing table (services) in my Postgres database. How do I instantiate this table object so I can do a bulk_insert with it?

我看到了这样的答案: Alembic bulk_insert到带有模式的表中,但我想避免重新定义模式再次在迁移.

I saw answers like this: Alembic bulk_insert to table with schema but I want to avoid redefining the schema again in the migration.

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


def upgrade():
    """Up migration."""


services = sa.MetaData().Services()

op.bulk_insert(services,
    [   
        {
        'id': 88,
        'name':'Test 1',
        'is_active': 'true',
        'include_in_broker_fee': 'true',
        'is_domestic': 'true',
        'is_international': 'true'
        },
        {
        'id': 89,
        'name':'Test 2',
        'is_active': 'true',
        'include_in_broker_fee': 'true',
        'is_domestic': 'true',
        'is_international': 'true'
        }
   ])

推荐答案

为了更新如上所示的表,您需要对其进行定义,以便sqlalchemy知道要更新的内容.使用alchemy的MetaData()对象执行此操作非常简单,实际上您几乎已经掌握了它.尝试这样的事情:

In order to update the table as you've shown above you'll need to define it so sqlalchemy knows what to update. Doing this with alchemy's MetaData() object is pretty straightforward, in fact you almost have it. Try something like this:

    from sqlalchemy import Table, MetaData

    meta = MetaData(bind=op.get_bind())
    services = Table('services', meta)

现在已经定义了表,您可以利用alchemy的批量更新方法.为此,请参考他们的文档,其中显示了bulk_insert_mappings()和bulk_save_objects()的几个示例- http://docs.sqlalchemy.org/en/latest/faq/performance.html

Now that the table is defined you can leverage alchemy's bulk update methods. For this I refer you to this bit of their documentation where they show several examples of bulk_insert_mappings() and bulk_save_objects() --- http://docs.sqlalchemy.org/en/latest/faq/performance.html

这篇关于如何使用Alembic/SQLAlchemy将表对象实例化为bulk_insert行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆