在admin中内联编辑时Django触发父模型保存 [英] Django trigger parent model save when editing inline in admin

查看:74
本文介绍了在admin中内联编辑时Django触发父模型保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与另一个模型(孩子)一对多关系的模型(父母)。父模型的保存方法被覆盖:

I have a model (Parent) with one-to-many relation to another model (Child). The save method of Parent model is overwritten:

class ParentModel(models.Model)
    (...)

    def save(self, *args, **kwargs):
        (...) # Do sth with the model
        super(ParentModel, self).save(*args, **kwargs)

class ChildModel(models.Model):
    parent= models.ForeignKey(ParentModel)

在管理面板中,使用父模型页面上的StackedInline显示多个子模型对象。如果父字段被编辑并保存,则调用save方法。当仅编辑子字段时,Django不会调用父对象的save方法(这是预期的,因为未做任何更改)。

In admin panel multiple Child models objects are displayed using StackedInline on Parent model's page. If a field of parent is edited and saved, the save method is called. When only child's fields are edited, Django do not call the save method of parent (as expected, because nothing changed).

即使只编辑了一个孩子,强制保存父母的最佳方法是什么(这样我的覆盖方法就可以了)?

What is the best way to force saving the parent, even if only child was edited (so that my overwritten method does it's stuff)?

推荐答案

您有一些解决方案。这样,从简单到复杂:

You have a few solutions. Here goes, from simpler to more complex:

您可以为 save 方法> ChildModel 调用 ParentModel.save

您还可以连接到 ChildModel post_save pre_save 信号。

You could implement a custom save method for ChildModel that calls ParentModel.save.
You could also connect to your ChildModel's post_save or pre_save signal.

现在,如果您要一次更新很多 ChildModel 实例,这两个解决方案将变得很烦人,因为您将调用 ParentModel.save 多次,可能没有目的。

然后,您可能想使用以下内容:

覆盖您的 ParentModel ModelAdmin.change_view 处理您的逻辑;但是,这非常棘手。

Now, these two solutions will prove annoying if you're going to update a lot of ChildModel instances at once, as you will be calling ParentModel.save several times, maybe without purpose.
You might then want to use the following:
Override your ParentModel's ModelAdmin.change_view to handle your logic; this is pretty tricky however.

我对您遇到的行为感到非常惊讶,从检查源代码开始,无论如何应该保存对象;是否编辑。

I'm however pretty surprised by the behavior your're encountering, from checking the source, the object should be saved anyway; edited or not.

这篇关于在admin中内联编辑时Django触发父模型保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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