I am adding date_added and date_modified fields to a bunch of common models in my current project. I am subclassing models.Model and adding the appropriate fields, but I want to add automated save behavior (i.e: evey time anyone calls MyModel.save(), the date_modified field gets updated. I see two approaches: overriding the save() method or adding a pre_save signal handler in the abstract base class.
class CommonData(models.Model):
date_added = models.DateTimeField(default=datetime.datetime.today,null=False,blank=False)
date_modified = models.DateTimeField(default=datetime.datetime.today,null=True,blank=True)
# register a handler for the pre_save to update date_modified
def pre_save_handler(sender, **kwargs):
date_modified = datetime.datetime.today
def __init__():
pre_save.connect(pre_save_handler, sender=self)
or
class CommonData(models.Model):
date_added = models.DateTimeField(default=datetime.datetime.today,null=False,blank=False)
date_modified = models.DateTimeField(default=datetime.datetime.today,null=True,blank=True)
# overriding save
def save(force_insert=False,force_update=False):
date_modified = datetime.datetime.now
return models.Model.save(force_insert, force_update)
I'm new to Django and Python and wondered which approach was more "django"? Which is more efficient? which is the "right" way to do this?