Django – Overriding the Model.create() method?

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)

Leave a Comment