今天要來使用ORM來寫入model data,讓我們能針對model data做新增、讀取、更新和刪除(CRUD)。
基本上會用這三種:
.create(values) 在model 上建立一筆新紀錄 會傳回已建立的紀錄
.write(values) 使用已有的值,更新recordest (returns nothing)
.unlink() 從資料庫刪除紀錄,(returns nothing)
ex:我們要預防在「Borrowed」或「Returned」的states,直接建立新的記錄。
(create)到library_checkout/models/library_checkout.py
@api.model
def create(self, vals):
new_record = super().create(vals)
if new_record.stage_id.state in ("open", "close"):
raise exceptions.UserError(
"State not allowed for new checkouts."
)
return new_record
ex: 租借出去的書,應該要持續追蹤書籍的借出日期和歸還日期。
(write)先到library_checkout/models/library_checkout.py,新增兩個日期欄位
checkout_date = fields.Date(readonly=True)
close_date = fields.Date(readonly=True)
回到library_checkout/models/library_checkout.py
def write(self, vals):
old_state = self.stage_id.state
super().write(vals)
new_state = self.stage_id.state
if not self.env.context.get("_checkout_write"):
if new_state != old_state and new_state == "open":
self.with_context(_checkout_write=True).write(
{"checkout_date": fields.Date.today()})
if new_state != old_state and new_state == "done":
self.with_context(_checkout_write=True).write(
{"close_date": fields.Date.today()})
return True
另外原本request date預設為今天,如果被更改的話,應該要向使用者提醒,運用onchange來修改,只會在:
還是到library_checkout/models/library_checkout.py
@api.depends('member_id')
def _compute_request_date_onchange(self):
today_date = fields.Date.today()
if self.request_date != today_date:
self.request_date = today_date
return {
"warning": {
"title": "Changed Request Date",
"message": "Request date changed to today!",
}
}
checkout_date = fields.Date(readonly=True)
close_date = fields.Date(readonly=True)