sqlalchemy插入与关系的多个对象

发布于 2025-01-24 19:44:20 字数 772 浏览 0 评论 0原文

我正在尝试创建许多对象。当前,它是通过调用session.add()然后在创建每个对象上的 session.flush()来完成的。这是不好的,因为创建了500多个以上的对象,因此每个对象都会执行影响性能的查询。我正在尝试优化这一点。

为了提供一些背景,这是我的对象看起来像:

class Metric:
    data: str
    fk_document_id: int (relationship)
    fk_user_id: int (relationship)

要突出显示的关键内容,此对象中有2个关系,使用SQLalchemy提供的Reltake属性实现。

我的第一个去更改代码以使用bulk_save_objects(),但是此方法不能保存关系,并且还需要session.commit(),理想情况下我不是之所以这样做,是因为在创建Metric对象之后,此交易有可能会退缩。

然后,我找到了add_all(),但是无论如何,这都会对每个对象执行add(),因此我认为它不会对当前的性能产生很大影响。

我看不到任何其他方法,所以我的问题是,在这种情况下是否有一种方法可以使用bulk_save_objects()持续关系,并且可能不需要提交。另外,如果有另一种我看不到的方法,请告诉我。

I am trying to create many objects. Currently it is done by calling session.add() then session.flush() upon each object being created. This is bad because there are over 500+ objects being created so each of them performs a query which affects performance. I am trying to optimise this.

To give some background, here is how my object roughly looks like:

class Metric:
    data: str
    fk_document_id: int (relationship)
    fk_user_id: int (relationship)

Key thing to highlight, there are 2 relationships in this object, implemented using the relationship property that SQLAlchemy offers.

My first go was to change the code to use bulk_save_objects() however this method does not save the relationships and also requires a session.commit() which I'd ideally not do because there is a chance this transaction could get rolled back after the creation of the Metric objects.

Then I found add_all() however this performs an add() for each object anyways, so I do not think it will impact the current performance much.

I can't see any other approach, so my question is if there is a way in this case to use bulk_save_objects() to persist relationships and possibly not require a commit. Alternatively, if there is another method to do this that I do not see, please let me know.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文