The Django docs only list examples for overriding save()
and delete()
. However, I'd like to define some extra processing for my models only when they are created. For anyone familiar with Rails, it would be the equivalent to creating a :before_create
filter. Is this possible?
views:
279answers:
2
+3
A:
Overriding __init__()
will allow you to execute code when the model is instantiated. Don't forget to call the parent's __init__()
.
Ignacio Vazquez-Abrams
2010-02-21 23:42:09
Ah yes this was the answer. Don't know how I overlooked this. Thanks Ignacio.
bobthabuilda
2010-02-21 23:57:11
+3
A:
Overriding __init__()
would cause code to be executed whenever the python representation of object is instantiated. I don't know rails, but a :before_created
filter sounds to me like it's code to be executed when the object is created in the database. If you want to execute code when a new object is created in the database, you should override save()
, checking if the object has a pk
attribute or not. The code would look something like this:
def save(self, *args, **kwargs):
if not self.pk:
#This code only happens if the objects is
#not in the database yet. Otherwise it would
#have pk
super(MyModel, self).save(*args, **kwargs)
Zach
2010-02-22 14:35:39
I've actually found a solution using signals: http://docs.djangoproject.com/en/dev/topics/signals/ (the pre_save signal, specifically). However, this seems to be a much more pragmatic solution. Thanks a bunch.
bobthabuilda
2010-02-24 04:16:18
nice hack. I'd still prefer to override the create method as I'd like to add a logging.info call after creation of a new object. Calling it before and you have chance of that the the call to the parent method fail...
PhilGo20
2010-03-25 16:34:34
I assume you mean overriding the manager method `create`? That's an interesting solution, but it wouldn't work in cases when the object is being created using `Object(**kwargs).save()` or any other variation on that.
Zach
2010-03-25 17:07:33