django 表单保存不能用于更新模型实例?

django form save can't be used update a model instance?

我正在使用 django 1.8.4

djanog.forms.models.BaseModelForm.save内容如下

def save(self, commit=True):
    """
    Saves this ``form``'s cleaned_data into model instance
    ``self.instance``.

    If commit=True, then the changes to ``instance`` will be saved to the
    database. Returns ``instance``.
    """
    if self.instance.pk is None:
        fail_message = 'created'
    else:
        fail_message = 'changed'
    return save_instance(self, self.instance, self._meta.fields,
                         fail_message, commit, self._meta.exclude,
                         construct=False)

save_instance有这个..

def save_instance(form, instance, fields=None, fail_message='saved',
                  commit=True, exclude=None, construct=True):
    """
    Saves bound Form ``form``'s cleaned_data into model instance ``instance``.

    If commit=True, then the changes to ``instance`` will be saved to the
    database. Returns ``instance``.

    If construct=False, assume ``instance`` has already been constructed and
    just needs to be saved.
    """
    if construct:
        instance = construct_instance(form, instance, fields, exclude)

基本上,上面的代码(save_instance)仅在construct = True时更新实例,但django代码一直通过construct = False

这是 1.8.4 中的错误吗? :(

我刚刚检查过代码在 1.8.9 之前保持不变

BaseModelForm._post_clean中调用了construct_instance方法:

# BaseModelForm._post_clean()
# Update the model instance with self.cleaned_data.
self.instance = construct_instance(self, self.instance, opts.fields, construct_instance_exclude)

调用此函数时,您的 "instance" 将使用表单数据进行更新。

注意_post_clean作为BaseForm.full_clean的一部分被调用,通常被is_valid间接调用。这意味着如果您不验证您的表单,调用 save 方法将在新实例上失败,或者无法更新旧实例。