使用SQLAlchemy ORM批量插入并返回主键 [英] Bulk insert with SQLAlchemy ORM and return primary keys

查看:115
本文介绍了使用SQLAlchemy ORM批量插入并返回主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用bulk_save_objectsbulk_insert_mappings将字典列表插入表中.有什么方法可以获取每个条目带有主键的对象列表吗?

I am trying to insert a list of dictionaries into a table using bulk_save_objects or bulk_insert_mappings. Is there any way I can get the list of objects with primary key for each entry?

try:
    cycle_object_list = []
    for cycle in cycle_list:
        period = Period()
        for k, v in cycle.items():
            setattr(period, k, v)
        cycle_object_list.append(period)

    db.session.bulk_save_objects(cycle_object_list)
    db.session.commit()
    print(cycle_object_list)
except Exception:
    db.session.rollback()
    raise
finally:
    db.session.close()

我期望像[Period.49, Period.50, Period.51]

但是实际结果是[Period.None,Period.None,Period.None]

But the actual result is [Period.None, Period.None, Period.None]

推荐答案

给定的对象不会添加到会话中,并且不会在其上建立任何其他状态,除非还设置了return_defaults标志,在这种情况下,将填充主键属性和服务器端默认值.

The objects as given are not added to the session and no additional state is established on them, unless the return_defaults flag is also set, in which case primary key attributes and server-side default values will be populated.

所以这可能起作用:

try:
    cycle_object_list = []
    for cycle in cycle_list:
        period = Period()
        for k, v in cycle.items():
            setattr(period, k, v)
        cycle_object_list.append(period)

    db.session.bulk_save_objects(cycle_object_list, return_defaults=True)
    db.session.commit()
    print(cycle_object_list)
except Exception:
    db.session.rollback()
    raise
finally:
    db.session.close()

这篇关于使用SQLAlchemy ORM批量插入并返回主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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