sqlalchemy插入与关系的多个对象
我正在尝试创建许多对象。当前,它是通过调用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论