0

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?

1

1 Answer 1

1

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' 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.