Django:获取管理员 save_model 中的所有内联对象

Django: Get all inline objects in Admin's save_model

我有两个相关的(通过 foreignKey 关系)模型,并为带有内联的父级创建了管理模型。在某个用例中,我需要获取所有相关模型并使用它们来更新父模型的 1 个特定字段。什么是有效的方法?

我的模特:

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]
    ...

我要的是类似这样的东西:

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)

save_model方法在相关对象保存前执行。这是显而易见的,因为相关对象必须引用模型的主键。

您可能正在寻找 save_related 方法。


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()