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

前端 未结 4 1053
感情败类
感情败类 2020-12-08 22:33

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

For example:

in models.py



        
4条回答
  •  醉酒成梦
    2020-12-08 22:47

    I was having issues with the answers in this post, so I figured out a more concise answer. I was having an issue because using django-fsm, the other answers here would try to save the model multiple times (once for every formset) rather than once at the end.

    def save_model(self, request, obj, form, change):
        if not obj.pk: # call super method if object has no primary key 
            super(YourAdmin, self).save_model(request, obj, form, change)
        else:
            pass # don't actually save the parent instance
    
    def save_related(self, request, form, formsets, change):
        form.save_m2m()
        for formset in formsets:
            self.save_formset(request, form, formset, change=change)
        super(YourAdmin, self).save_model(request, form.instance, form, change)
    

    This essential just flips the order of save_model and save_related as called in Django ModelAdmin source

提交回复
热议问题