简体   繁体   English

在Python SQLAlchemy中使用数据库模型对象,而不会干扰数据库事务

[英]Use a database model object in Python SQLAlchemy without interfering with database transactions

I'm fetching some objects from database using SQL Alchemy. 我正在使用SQL Alchemy从数据库中获取一些对象。 Because I'm using the objects in Flask and Jinja to create web pages for the user, it's sometimes convenient to edit raw database values. 因为我正在使用Flask和Jinja中的对象为用户创建网页,所以有时可以方便地编辑原始数据库值。 This could mean swapping user id's for legible user names, for example. 例如,这可能意味着将用户ID替换为清晰的用户名。

When I do this to the model objects returned by my database function (see example below), I start getting errors. 当我对数据库函数返回的模型对象执行此操作时(请参见下面的示例),我开始收到错误消息。 I suspect this has to do with the fact that SQLAlchemy 'thinks' that I want to alter database rows because I am editing attributes of the Model class/object. 我怀疑这与SQLAlchemy认为我要更改数据库行有关,因为我正在编辑Model类/对象的属性。

However, I only want to use them as 'flat' data-only objects, for this case. 但是,在这种情况下,我只想将它们用作“平面”纯数据对象。 What is the best way to circumvent this problem? 避免此问题的最佳方法是什么?

if not sql_session.query(Client).count():

    return {"state" : False, "clients" : [] }

else: 

    return {"state" : True, "clients" : sql_session.query(Client).filter().all() }

make_transient对象之前: http : make_transient

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM