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

7

在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)
1个回答

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.
    """
    ...

补充说明:所有行号适用于django版本(1, 3, 0, 'alpha', 0)


2
实际上,在某些情况下,惰性保存可能更可取。惰性保存可以在程序员不费吹灰之力的情况下使事务变得更短。请参见https://dev59.com/ZE7Sa4cB1Zd3GeqP8Phx - Jonathan Livni
同意,好答案,但有时候懒惰保存确实很有意义。 - Seth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接