kabukiman
kabukiman

Reputation: 473

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

I have a Profile model and NotificationSettings model with OneToOne relation. There is more than one way to create Profile, but NotificationSettings must be created with all of them. I don't want to write same code for every view that creates Profile. So i was hoping that there is some event that i can track so NotificationSettings would be created automatically. Something similar to RubyOnRails' after_create callback

Upvotes: 1

Views: 141

Answers (1)

Luiz
Luiz

Reputation: 2055

You can overwrite the save method of the models to do what you want like this

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

See more in the docs here

Upvotes: 1

Related Questions