是否可以在 Django 中自动创建父创建时的相关对象?

Is it possible to create related objects on parent creation automatically in Django?

我有一个 Profile 模型和一个具有 OneToOne 关系的 NotificationSettings 模型。创建配置文件的方法不止一种,但必须使用所有方法创建 NotificationSettings。我不想为创建配置文件的每个视图编写相同的代码。所以我希望我可以跟踪一些事件,以便自动创建 NotificationSettings。类似于 RubyOnRails 的 after_create 回调

你可以覆盖模型的保存方法来做你想做的事

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def save(self, *args, **kwargs):
        do_something()
        super().save(*args, **kwargs)  # Call the "real" save() method.
        do_something_else()

在文档中查看更多内容here