为什么 Django Admin 使用 commit=False 调用 UserCreationForm save 方法?

Jow*_*ado 6 django django-admin

django 管理员实际上在哪里保存它的模型?

我想打印一些仅在保存后创建的模型字段,但 UserCreationForm 保存方法总是使用 commit=False 调用,并且似乎返回用户,因此保存发生在其他地方。

class MyUserCreationForm(UserCreationForm):
    ...
    def save(self, commit=True):
        # django admin calling this with commit=False... save occurs somewhere else.
        ...
        if commit:
            print("this never gets printed")
            user.save()

        # line below prints nothing
        print(user.field_set_after_model_is_saved)

        return user
Run Code Online (Sandbox Code Playgroud)

ps:我的模型正常保存,只是没有达到我的预期。

小智 -1

\n

此 save() 方法接受一个可选的 commit 关键字参数,该参数接受 True 或 False。如果您使用 commit=False 调用 save(),则它将返回一个尚未保存到数据库的对象。在这种情况下,\xe2\x80\x99 由您决定对生成的模型实例调用 save() 。如果您想在保存对象之前对其进行自定义处理,或者您想使用专用模型保存选项之一,这将非常有用。默认情况下 commit 为 True。

\n
\n\n

来自文档

\n\n

当你使用commit=False,您还没有保存在数据库中,它允许您在保存之前管理对象。

\n\n

例如:

\n\n
class UserForm(forms.ModelForm):\n    ...\n    def save(self):\n        # Sets username to email before saving\n        user = super(UserForm, self).save(commit=False)\n        user.username = user.email\n        user.save()\n        return user\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果第一次保存不使用commit=False,则保存了两次,代表更多的数据库操作。\n在你的情况下,我认为你可以使用 post_save 信号,请看这里

\n