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 created
keyword 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:
def save(self, *args, **kwargs):
if not self.pk: # object is being created, thus no primary key field yet
self.name += " is a hero"
super(Hero, self).save(*args, **kwargs)
Note that Djagno's bulk_create
method will skip triggering either the post-save signal or calling save
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With