因爲這是不可用的數據庫,但一些外部文件,我想創建一個包含數據從外部文件中讀取一個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