David542
David542

Reputation: 110257

How to see if a field changed in model save method

I want to see if my title field changed in a save method. Here is what I have so far:

class Answer(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()

    def save(self, *args, **kwargs):
        if self.pk:
            answer_prev = Answer.objects.get(pk=self.pk)
            if answer_rev.title != self.title:
                log.info('TITLE HAS CHANGED!!')

Is there a better way to do this?

Upvotes: 0

Views: 538

Answers (1)

Manuel Alvarez
Manuel Alvarez

Reputation: 2199

I think the best solution is use django model pre_save signal.

Before save, instance in db is still original one, but instance param has the new values, so you can check if a field has changed.

from django.db import models
from django.dispatch import receiver

@receiver(models.signals.pre_save, sender=Answer)
def prepare_save(sender, instance, **kwargs):
    try:
        current_instance = sender.objects.get(pk=instance.pk)
        if current_instance.title != instance.title:
            print 'Title changed to %s!' % instance.title
    except sender.DoesNotExist:
        print 'new answer. No title change'

Upvotes: 1

Related Questions