Login

auto_now using signals

Author:
ddanier
Posted:
July 10, 2008
Language:
Python
Version:
.96
Score:
-2 (after 4 ratings)

There has been some discussion about removing auto_now and auto_now_add some time ago. auto_now_add can be replaced be using a callable default value, auto_now can't. So I wrote this litte function for my current project (older ones still use auto_add) to fill the gap...but I'm not sure if auto_now will be removed at all.

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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 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.

#

Please login first before commenting.