Django - 模型保存()方法是懒惰的吗? [英] Django - Are model save() methods lazy?

查看:24
本文介绍了Django - 模型保存()方法是懒惰的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型 save() 方法在 django 中是惰性的吗?

Are model save() methods lazy in django?

例如,django 将在以下代码示例中的哪一行访问数据库?

For instance, at what line in the following code sample will django hit the database?

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 方法不是.

It does not make much sense to have a lazy save, does it? Django's QuerySets are lazy, the model's save method is not.

来自 django 源码:

From the django source:

django/db/models/base.py,第 424–437 行:

django/db/models/base.py, lines 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 行):

Then, save_base does the heavy lifting (same file, lines 439–545):

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

django/db/transaction.py 的第 167–178 行中,您会发现:

And in django/db/transaction.py, lines 167–178, you'll find:

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

<小时>

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

这篇关于Django - 模型保存()方法是懒惰的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆