auto_now using signals

1
2
3
4
5
6
7
8
# Takes model and fieldname and sets field to current datetime on pre_save
def auto_now_on_save(model, fieldname):
	from django.db.models import signals
	from django.dispatch import dispatcher
	def _update_datefield(instance):
		from datetime import datetime
		setattr(instance, fieldname, datetime.now())
	dispatcher.connect(_update_datefield, signal=signals.pre_save, sender=model, weak=False)

More like this

  1. db_dump.py - for dumpping and loading data from database by limodou 6 years, 3 months ago
  2. Improved Pickled Object Field by taavi223 3 years, 9 months ago
  3. Admin definition converter (for newforms-admin) by willhardy 4 years, 10 months ago
  4. SSL Decorator by pjs 4 years, 2 months ago
  5. Complex Formsets, Redux by smagala 3 years, 2 months ago

Comments

ericflo (on July 10, 2008):

It's good to know that for now that Django's signals are a fairly large performance hit. To remedy this, you can simply do this:

def save(self):
    self.myfield = datetime.now()
    super(MyModel, self).save()

It's one more line than if you import your solution and apply it to a field, but doesn't incur the performance penalty that signals currently entail.

#

(Forgotten your password?)