Let’s say I have a class named Hero with a field named “name”. Everytime a new Hero object is created, I want to append " is a hero". Can I use __init__ for that? Or is there a django-specific method I can override for that?
class Hero(modes.Model)
name = models.CharField(max_length=100)
def __init__(self, *args, **kwargs):
name += " is a hero"
super(Hero, self).__init__(*args, **kwargs)
If by “every time a new Hero object is created” you mean “every time a Hero record is created in the database,” then no, you don’t want to do this in the
__init__method, since that is called any time a Hero object is created in Python, including when you are just getting an existing record from the database.To do what you want, you can use Django’s post_save signal, checking in the signal callback that the
createdkeyword parameter is True and performing your “on creation” logic if so.Alternatively, and more straightforward and natural in certain cases, you can override Hero’s
save()method as follows:Note that Djagno’s
bulk_createmethod will skip triggering either the post-save signal or callingsave.