在 django admin 上编辑实际对象之前保存相关对象 [英] Save the related objects before the actual object being edited on django admin

查看:33
本文介绍了在 django admin 上编辑实际对象之前保存相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 django 管理表单上编辑实际对象之前保存相关对象?

Is it possible to save the related objects before the actual object being edited on a django admin form?

例如:

models.py

class Parent(model.Model):
    pass

class Child(model.Model):
    parent = models.ForeignKey(Parent)

@receiver(post_save,sender = Parent)
def notify_parent_save(sender, instance=None, **kwargs):
    print "Parent save"

@receiver(post_save,sender = Child)
def notify_child_save(sender, instance=None, **kwargs):
    print "Child saved"

admin.py

class ChildInline(admin.TabularInline):
    model = Child
    extra = 1

class ParentsAdmin(admin.ModelAdmin):
    inlines = [ChildInline]

admin.site.register(Parent,ParentsAdmin)

现在,在 django admin 中,如果我保存父对象,它将在控制台上输出.

Now, in django admin if I save a parent object, it will output on the console.

Parent save
Child save

我需要按照相反的顺序进行:

I need this to happen in revese order:

Child save
Parent save

推荐答案

以下先救孩子:

class ParentAdmin(admin.ModelAdmin):
    inlines = [ChildInline]

    def save_model(self, request, obj, form, change):
        pass # don't actually save the parent instance

    def save_formset(self, request, form, formset, change):
        formset.save() # this will save the children
        form.instance.save() # form.instance is the parent

这篇关于在 django admin 上编辑实际对象之前保存相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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