模型save()方法在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)
最佳答案
懒惰的保存没有多大意义,对吗? 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)
。关于database - Django-模型save()方法是否懒惰?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3212988/