2010-07-09 26 views
7

模型保存()方法在Django懶?Django - 模型保存()方法是否懶惰?

例如,在下面的代碼示例中,django會在數據庫中的哪一行?

my_model = MyModel() 
my_model.name = 'Jeff Atwood' 
my_model.save() 
# Some code that is independent of my_model... 
model_id = model_instance.id 
print (model_id) 

回答

7

懶惰的保存沒有多大意義,是嗎? Django的QuerySets是懶惰的,該模型的save方法不是。

從django的源:

django/db/models/base.py,線424-437:

def save(self, force_insert=False, force_update=False, using=None): 
    """ 
    Saves the current instance. Override this in a subclass if you want to 
    control the saving process. 

    The 'force_insert' and 'force_update' parameters can be used to insist 
    that the "save" must be an SQL insert or update (or equivalent for 
    non-SQL backends), respectively. Normally, they should not be set. 
    """ 
    if force_insert and force_update: 
     raise ValueError("Cannot force both insert and updating in \ 
      model saving.") 
    self.save_base(using=using, force_insert=force_insert, 
     force_update=force_update) 

save.alters_data = True 

然後,save_base確實繁重(同一個文件,行439-545):

... 
transaction.commit_unless_managed(using=using) 
... 

而在django/db/transaction.py,第167-178行,你會發現:

def commit_unless_managed(using=None): 
    """ 
    Commits changes if the system is not in managed transaction mode. 
    """ 
    ... 

P.S.所有行號適用於django版本(1, 3, 0, 'alpha', 0)

+1

實際上,在某些情況下,懶惰保存會更好。懶惰的保存可以使程序員無需付出任何努力就可以實現更短的交易。看到http://stackoverflow.com/questions/3215833/django-keeping-save-based-transactions-short – Jonathan 2010-07-10 06:03:57

+0

同意,很好的答案,但是有時候,它有很多意義,有一個懶惰的保存。 – Seth 2014-06-15 01:22:23