Skip to content

Instantly share code, notes, and snippets.

@bernardoduarte
Created June 19, 2019 20:30
Show Gist options
  • Save bernardoduarte/146ec86f4e22926aefcd1268ac9b2750 to your computer and use it in GitHub Desktop.
Save bernardoduarte/146ec86f4e22926aefcd1268ac9b2750 to your computer and use it in GitHub Desktop.
Django Model Mixin for field change monitoring
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class HasChangedModelMixin(models.Model):
class Meta:
abstract = True
@classmethod
def from_db(cls, db, field_names, values):
# https://docs.djangoproject.com/en/1.10/ref/models/instances/#customizing-model-loading
instance = super(HasChangedModelMixin, cls).from_db(db, field_names, values)
# customization to store the original field values on the instance
instance._loaded_values = dict(zip(field_names, values))
return instance
def has_field_changed(self, field_name):
if self._state.adding:
return False
return getattr(self, field_name) != self._loaded_values[field_name]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment