2017-04-26 235 views
-1

我有一個函數:繼續後嘗試已經失敗

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所以我使用的嘗試,除了跳過錯誤時它試圖輸入數據這已經在我得到數據庫。我怎樣才能壓縮這段代碼?我覺得它有很多不必要的代碼行。

+0

首先,[*不要使用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

+0

當您嘗試**保存**重複的對象時,會引發*唯一錯誤*。所以,不需要所有這些'嘗試...除了'條款。只需在'try ... except'子句中移動'newobj.save()'。 – xyres

回答

1

Django很聰明:就像在其中一條評論中說的那樣,只有在調用save()方法時纔會引發錯誤。在此之前,Article是一個普通的Python對象。你應該會看起來更象這樣的:

from psycopg2 import IntegrityError # this is the actual error raised by psycopg2 (the postgres python driver) 

from article.models import Articles 

for item in all_item_tags: 
    try: 
     new_article = Articles(
      pub_date=item.contents[9].contents[0],   
      title=item.contents[1].contents[0], 
      description=item.contents[5].contents[0], 
      image=get_the_picture(item.contents[7]) 

     new_article.save() # this is where the actual save happens 
    except IntegrityError: 
     # Handle the exception here 

另一個(更高級)選項是重寫save()方法,把你的邏輯存在。

也就是說,你也可以使用get_or_created來做到這一點。它看起來像這樣:

for item in all_item_tags: 
    # this methods returns a boolean True of False if the object is already in the DB. 
    # use your unique identifier here 
    article, created = Article.objects.get_or_create(unique_id=...) 

    # You can then do a classic if-else without handling any errors... 
    if created: 
     # Great! The object a 
    else: 
     # the object exist, do something with it or not... 

但是,有幾件事我會建議。我的感覺是,你沒有真正瞭解Python就潛入Django。 Django是一個很大的野獸,它使很多東西非常方便(幾乎神奇的),但它仍然是Python。如果你潛入的太深,某些事情就會中斷,那麼你很難知道發生了什麼。我建議你進一步提高你對Python的知識(這是一種令人驚歎的語言,所以它會很有趣),然後回到Django,或者從像Flask這樣的小型框架開始,它可以減少魔法!現在,這裏有一個關於錯誤處理的官方文檔的鏈接,所以你可以更多地瞭解它。另外,Django的確有很好的doc,所以如果出現問題,我會先看看。

乾杯和快樂的編碼!