I have a django model, and I need to compare old and new values of field BEFORE saving.
I\'ve tried the save() inheritence, and pre_save signal. It was triggered cor
Django 1.8+ and above (Including Django 2.x and 3.x), there is a from_db
classmethod, which can be used to customize model instance creation when loading from the database.
Note: There is NO additional database query if you use this method.
Here is the link to the official docs Model instance - Customize model loading
from django.db import Model
class MyClass(models.Model):
@classmethod
def from_db(cls, db, field_names, values):
instance = super().from_db(db, field_names, values)
# save original values, when model is loaded from database,
# in a separate attribute on the model
instance._loaded_values = dict(zip(field_names, values))
return instance
So now the original values are available in the _loaded_values
attribute on the model. You can access this attribute inside your save
method to check if some value is being updated.
class MyClass(models.Model):
field_1 = models.CharField(max_length=1)
@classmethod
def from_db(cls, db, field_names, values):
...
# use code from above
def save(self, *args, **kwargs):
# check if a new db row is being added
# When this happens the `_loaded_values` attribute will not be available
if not self._state.adding:
# check if field_1 is being updated
if self._loaded_values['field_1'] != self.field_1:
# do something
super().save(*args, **kwargs)