【问题标题】:Why does Django Admin calls UserCreationForm save method with commit=False?为什么 Django Admin 使用 commit=False 调用 UserCreationForm 保存方法?
【发布时间】:2018-09-24 04:51:11
【问题描述】:

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

p.s:我的模型正在正常保存,只是没有达到我的预期。

【问题讨论】:

  • 请向模型管理员展示您在哪里使用表单,以及您是如何注册该模型管理员的。

标签: django django-admin


【解决方案1】:

这个 save() 方法接受一个可选的 commit 关键字参数,它 接受 True 或 False。如果您使用 commit=False 调用 save(), 然后它将返回一个尚未保存到 数据库。在这种情况下,您可以在结果上调用 save() 模型实例。如果您想在 保存之前的对象,或者如果您想使用其中一个 专门的模型保存选项。提交默认为真。

来自docs

当您使用commit=False 时,您还没有保存到数据库中,它可以让您在保存之前管理对象。

例如:

class UserForm(forms.ModelForm):
    ...
    def save(self):
        # Sets username to email before saving
        user = super(UserForm, self).save(commit=False)
        user.username = user.email
        user.save()
        return user

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

【讨论】:

    猜你喜欢
    • 2012-10-02
    • 2015-10-24
    • 2018-07-23
    • 2021-01-13
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    相关资源
    最近更新 更多