The best way to add a generic date is date_added, date_modified for many models in Django

I am adding the date_added and date_modified fields to a bunch of generic models in my current project. I will subclass models. Modeling and adding appropriate fields, but I want to add automatic saving of behavior (i.e. time evey, when someone calls MyModel.save (), the date_modified field is updated. I see two approaches: overriding the save () method or adding a pre_save signal handler in an 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 wondering which approach was more "django"? Which is more efficient? which is the "right" way to do this?

+4
source share
4 answers

Since you're new to Django, you can find useful Django extensions:

http://code.google.com/p/django-command-extensions/

... which conveniently includes TimeStampedModel, you can get your models:

http://code.google.com/p/django-command-extensions/wiki/ModelExtensions

An abstract base class model that provides self-sustaining "created" and "modified" fields.

+4
source

Have you tried looking at DateTimeField auto_now=True and auto_now_add=True ? They do what you need automatically. Otherwise, there is no real difference between performing override preservation and signal processing — in fact, the pre_save signal is called from the django model's save method.

Docs: http://docs.djangoproject.com/en/dev/ref/models/fields/#datefield

+4
source

You can define them in an Abstract base class and then inherit from it. This is similar to having MixIn, which also defines the model fields.

+2
source

Note that auto_now_add and auto_now use pre_save , which does not work with bulk_create or update . Thus, in your MySQL, for example, the date_added field will be "0000-00-00 00:00:00", and you may get a warning: "Warning: the column" date_added "cannot be null." That way you can use auto_now *, but you have to be careful.

+1
source

All Articles