Last active
January 24, 2018 15:36
-
-
Save jeruyyap/8d63455c7a1682fb9e71eae93bb24a20 to your computer and use it in GitHub Desktop.
Django "Last Modified" and "Created" timestamps as custom field types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This is a simple implementation of "last modified" and "created" timestamps custom field types for Django. | |
I used this in a few projects due to talk of deprecating "auto_now" and "auto_now_add" for DateTime fields. | |
It doesn't seem as necessary now that said options appear to be staying in Django. | |
That said, I figured I might as well have this snippet just in case. | |
""" | |
from django.db import models | |
from django.utils import timezone | |
class TimeStampLastModifiedField(models.DateTimeField): | |
""" | |
Custom field for last updated timestamp | |
""" | |
def pre_save(self, model_instance, add): | |
return timezone.now() | |
class TimeStampCreatedField(models.DateTimeField): | |
""" | |
Custom field for create timestamp | |
""" | |
def pre_save(self, model_instance, add): | |
if not add: | |
return getattr(model_instance, self.attname) | |
return timezone.now() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment