Skip to content

Instantly share code, notes, and snippets.

@dnozay
Created February 23, 2012 18:35
Show Gist options
  • Save dnozay/1894258 to your computer and use it in GitHub Desktop.
Save dnozay/1894258 to your computer and use it in GitHub Desktop.
Fixture-friendly DateTimeField w.r.t auto_now, auto_now_add
# Fixture-friendly DateTimeField w.r.t auto_now, auto_now_add
# >>> created_at = AutoDateTimeField(auto_now_add=True)
# >>> updated_at = AutoDateTimeField(auto_now=True)
# see the following links for context
# http://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add
# http://groups.google.com/group/django-developers/browse_thread/thread/4cd631c225cb4e52
class AutoDateTimeField(models.DateTimeField):
'''Fixture friendly DateTimeField
>>> created_at = AutoDateTimeField(auto_now_add=True)
>>> updated_at = AutoDateTimeField(auto_now=True)
'''
def pre_save(self, model_instance, add):
value = getattr(model_instance, self.attname)
if value is None:
return super(DateTimeField, self).pre_save(model_instance, add)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment