【发布时间】:2011-02-17 18:34:29
【问题描述】:
由于遗留数据在数据库中不可用,但在一些外部文件中不可用,我想创建一个 SQLAlchemy 对象,其中包含从外部文件读取的数据,但如果我执行 session.flush()
我的代码如下所示:
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
除了在应用程序中稍后执行的session.flush() 之外,一切正常,SQLAlchemy 尝试将创建的 Phone 对象写入数据库(幸运的是,这没有成功,因为 phone.state 比数据类型允许的长),这会破坏发出刷新的功能。
有什么方法可以阻止 SQLAlchemy 尝试编写这样的对象?
更新
虽然我没有找到任何东西
using_mapper_options(save_on_init=False)
在 Elixir 文档中(也许你可以提供一个链接?),在我看来值得一试(我更喜欢一种方法来防止编写单个实例而不是整个实体)。
起初似乎该语句没有效果,我怀疑我的 SQLAlchemy/Elixir 版本太旧,但后来我发现与 PurchaseOrderPosition 实体(我没有修改)的连接是用
phone.purchaseOrderPosition = self.getLegacyOrder(ident)
导致 phone 对象再次被写入。如果我删除该声明,一切似乎都很好。
【问题讨论】:
标签: python sqlalchemy python-elixir