Skip to content

Instantly share code, notes, and snippets.

@dannvix
Last active August 29, 2015 14:04
Show Gist options
  • Save dannvix/19635ee2b8f00a875f8e to your computer and use it in GitHub Desktop.
Save dannvix/19635ee2b8f00a875f8e to your computer and use it in GitHub Desktop.
Django models RecordStatusHistoryMixin (pre_save hook)
from django.db import models
from jsonfield import JSONField
from dirtyfields import DirtyFieldsMixin
import time
class RecordStatusHistoryMixin(DirtyFieldsMixin):
def save(self, *args, **kwargs):
if not self.pk:
# first create
current_time = int(time.time())
self.status_history.append(dict(
timestamp=current_time, status=self.status))
elif self.is_dirty():
dirty_fields = self.get_dirty_fields()
if "status" in dirty_fields:
# status changed, write history
current_time = int(time.time())
self.status_history.append(dict(
timestamp=current_time, status=self.status))
super(RecordStatusHistoryMixin, self).save(*args, **kwargs)
class Job(RecordStatusHistoryMixin, models.Model):
status = models.CharField(max_length=32)
status_history = JSONField(blank=True, default=[])
@dannvix
Copy link
Author

dannvix commented Aug 1, 2014

Should use self.pk to determine if it's first time (create). Fixed in rev #3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment