Django - 模型save()方法是否懒惰?

Jon*_*han 7 database django save django-models

django中的模型save()方法是否很懒?

例如,在以下代码示例中的哪一行将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)
Run Code Online (Sandbox Code Playgroud)

mik*_*iku 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
Run Code Online (Sandbox Code Playgroud)

然后,save_base重举(相同的文件,行439-545):

...
transaction.commit_unless_managed(using=using)
...
Run Code Online (Sandbox Code Playgroud)

django/db/transaction.py第167-178行,你会发现:

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

PS所有行号适用于django版本(1, 3, 0, 'alpha', 0).

  • 实际上,在某些情况下,延迟保存会更可取。延迟保存可以实现更短的事务,而无需程序员方面的任何努力。见 http://stackoverflow.com/questions/3215833/django-keeping-save-based-transactions-short (2认同)