gpt4 book ai didi

database - Django - 模型 save() 方法是懒惰的吗?

转载 作者:太空狗 更新时间:2023-10-30 01:47:20 25 4
gpt4 key购买 nike

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)

最佳答案

延迟保存没有多大意义,对吗? 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)

关于database - Django - 模型 save() 方法是懒惰的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3212988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com