Reputation: 127
In my Django MyModel
I've created a new field last_status_change
(a timestamp). Should be updated when that status changes.
However, even when a print
shows that last_status_change
is computed correctly, it doesn't get saved.
Is any field modification prohibited within save? What's the reason behind it? How to work around it?
class MyModel(models.Model):
first_name = models.CharField(max_length=100, verbose_name='Name')
confirmation_status = models.CharField(
choices=CONFIRMATION_STATUS_CHOICES,
default='registered', max_length=20
)
last_status_change = models.DateTimeField(null=True, blank=True)
def save(self, *args, **kwargs):
if self.pk:
original = MyModel.objects.get(pk=self.pk)
if original.confirmation_status != self.confirmation_status:
last_status_change = datetime.now()
return super(MyModel, self).save(*args, **kwargs)
Upvotes: 1
Views: 38
Reputation: 476574
You need to assign it to the self
object, so:
from django.utils import timezone
class MyModel(models.Model):
first_name = models.CharField(max_length=100, verbose_name='Name')
confirmation_status = models.CharField(
choices=CONFIRMATION_STATUS_CHOICES, default='registered', max_length=20
)
last_status_change = models.DateTimeField(null=True, blank=True)
def save(self, *args, **kwargs):
if self.pk:
original = MyModel.objects.get(pk=self.pk)
if original.confirmation_status != self.confirmation_status:
self.last_status_change = timezone.now()
return super().save(*args, **kwargs)
Upvotes: 1