Django - Check diference between old and new value when overriding save method

Francisco picture Francisco · Oct 18, 2012 · Viewed 8.8k times · Source

thanks for your time.

I'm on Django 1.4, and I have the following code: Its the overriden save method for my Quest model.

@commit_on_success
def save(self, *args, **kwargs):
    from ib.quest.models.quest_status_update import QuestStatusUpdate
    created = not self.pk

    if not created:
        quest = Quest.objects.get(pk=self)
        # CHECK FOR SOME OLD VALUE
    super(Quest, self).save(*args, **kwargs)

I couldn't find out a smart way of doing this. It seems very silly to me to have to make a new query for the object i'm currently updating in order to find out an old instance value.

Is there a better way to do this?

Thank you all.

Francisco

Answer

Simon Steinberger picture Simon Steinberger · Oct 17, 2014

You can store the old value inside the init method:

def __init__(self, *args, **kwargs):
    super(MyModel, self).__init__(*args, **kwargs)
    self.old_my_field = self.my_field

def save(self, *args, **kwargs):
    print self.old_my_field
    print self.my_field

You can probably use deepcopy or something alike to copy the whole object for later use in the save and delete methods.