views:

279

answers:

2

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?

+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
Ah yes this was the answer. Don't know how I overlooked this. Thanks Ignacio.
bobthabuilda
+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
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
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
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