我有一個函數:繼續後嘗試已經失敗
def save_to_models(all_item_tags):
from article.models import Articles
for item in all_item_tags:
newobj = Articles()
try:
newobj.pub_date =item.contents[9].contents[0]
except:
continue
try:
newobj.title =item.contents[1].contents[0]
except:
continue
try:
newobj.description =item.contents[5].contents[0]
except:
continue
try:
newobj.image =get_the_picture(item.contents[7])
except:
continue
newobj.save()
每個模型都有unique=True
所以我使用的嘗試,除了跳過錯誤時它試圖輸入數據這已經在我得到數據庫。我怎樣才能壓縮這段代碼?我覺得它有很多不必要的代碼行。
首先,[*不要使用bare'except' *](http://blog.codekills.net/2011/09/29/the-evils-of--except--/) - be具體關於什麼可能出錯。另一方面,如果你想要抑制一行的錯誤,並且你正在使用Python 3.4+,請參見['contextlib.suppress'](https://docs.python.org/3/library/contextlib.html#contextlib。壓制)。另外,像這樣對齊空白不是一個好主意。 – jonrsharpe
當您嘗試**保存**重複的對象時,會引發*唯一錯誤*。所以,不需要所有這些'嘗試...除了'條款。只需在'try ... except'子句中移動'newobj.save()'。 – xyres