我正在寫代碼從HTML表單中獲取數據並修改數據庫對象。我只想在數據庫對象上做一個put()如果有變化,所以我需要知道是否有任何改變。執行一些功能跟蹤,如果有任何返回true
到目前爲止,我已經嘗試了幾種方法,我將在代碼中進行說明。它們都使用下面的設置代碼:
def _addFormAttrToModel(self, obj, attr_name, new_attr):
if hasattr(obj, attr_name):
current_attr = getattr(obj, attr_name)
if current_attr == new_attr:
return False
setattr(obj, attr_name, new_attr)
return True
def addFormStringToModel(self, obj, attr_name):
new_attr = self.request.get(attr_name, None)
return self._addFormAttrToModel(obj, attr_name, new_attr)
第一個使用or
,以決定是否有任何方法調用的返回True。
updated=False
updated = self.addFormStringToModel(customer, "name") or updated
updated = self.addFormStringToModel(customer, "addr") or updated
updated = self.addFormStringToModel(customer, "phone") or updated
if updated:
customer.put()
,我已經實驗過另一種形式使用一組:
results= set()
results.add(self.addFormStringToModel(customer, "name"))
results.add(self.addFormStringToModel(customer, "addr"))
results.add(self.addFormStringToModel(customer, "phone"))
if True in results:
customer.put()
我真正喜歡做的是這樣的:
updated = self.addFormStringToModel(customer, "name") and \
self.addFormStringToModel(customer, "addr") and \
self.addFormStringToModel(customer, "phone")
if updated:
customer.put()
然而,經過停止執行第一個已更新的屬性。有更多pythonic的方式?