Home > OS >  Django: Get all inline objects in Admin's save_model
Django: Get all inline objects in Admin's save_model

Time:03-17

I have two related (via foreignKey relation) models and created admin model for parent with inlines. In a certain use-case, I need to fetch all related models and use those to update 1 particular field for parent model. What is the efficient way to do it?

My Models:

class ParentModel(BaseModel):
    text = models.CharField() # This is generated from inline children's data
    ...

class ChildModel(BaseModel):
    parent = models.ForeignKey(ParentModel, on_delete=models.RESTRICT)
    ...

class ChildModelInline(TabularInline):
    model = ChildModel

class ParentModelAdmin(admin.ModelAdmin):
    inlines = [ChildModelInline]
    ...

What I want is something similar to this:

class ParentModelAdmin(admin.ModelAdmin):
    inlines = [ChildModelInline]
    ...

    def save_model(self, request, obj, form, change):
        inline_objects = <get_all_inline_objects>
        obj.text = <generate_text(inline_objects)>

        super(ParentModelAdmin, self).save_model(request, obj, form, change)

CodePudding user response:

The save_model method is executed before the related objects are saved. This is obvious, because the related objects must reference the primary key of the model.

You are probably looking for the save_related method.


class ParentModelAdmin(admin.ModelAdmin):

    def save_related(self, request, form, formsets, change):
        super(ParentModelAdmin, self).save_related(self, request, form, formsets, change):
        # form.instance stores the saved object
        form.instance.text = ...
        form.instance.save() 


  • Related