Search code examples
djangodjango-modelsdjango-admindjango-signals

Save the related objects before the actual object being edited on django admin


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

For example:

in 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"

in admin.py

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

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

admin.site.register(Parent,ParentsAdmin)

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

Solution

  • The following will save the children first:

    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