因为这是不可用的数据库,但一些外部文件,我想创建一个包含数据从外部文件中读取一个SQLAlchemy的对象,但不写,如果我执行数据库遗留数据的session.flush()
如何创建非持久化Elixir/SQLAlchemy对象?
我的代码如下所示:
try:
return session.query(Phone).populate_existing().filter(Phone.mac == ident).one()
except:
return self.createMockPhoneFromLicenseFile(ident)
def createMockPhoneFromLicenseFile(self, ident):
# Some code to read necessary data from file deleted....
phone = Phone()
phone.mac = foo
phone.data = bar
phone.state = "Read from legacy file"
phone.purchaseOrderPosition = self.getLegacyOrder(ident)
# SQLAlchemy magic doesn't seem to work here, probably because we don't insert the created
# phone object into the database. So we set the id fields manually.
phone.order_id = phone.purchaseOrderPosition.order_id
phone.order_position_id = phone.purchaseOrderPosition.order_position_id
return phone
一切正常,只是在后面的应用程序SQLAlchemy的尝试写入创建电话对象数据库(幸好没有成功执行的session.flush()
,因为phone.state是比数据类型允许的更长),这打破了发出刷新的函数。
有没有办法阻止SQLAlchemy试图写这样的对象?
更新
虽然我没有找到长生不老药的文件(也许你可以提供一个链接?),在我看来,值得一试在
using_mapper_options(save_on_init=False)
什么(我会有一种方法可以防止单个实例被写入而不是整个实体)。
起初它似乎没有效果,我怀疑我的SQLAlchemy/Elixir版本太旧了,但后来我发现与
的PurchaseOrderPosition实体(我没有修改)的连接phone.purchaseOrderPosition = self.getLegacyOrder(ident)
导致电话对象再次被写入。如果我删除声明,一切似乎都很好。
我更新了我的答案。 – 2010-05-11 21:51:22