Django, How to update DateTimeField attribute only when one specific attribute is changed

Viewed 72

I would like to update the attribute date_assigned only when the attribute Customer is changed. I know that I have to overwrite the save function within the same model but i don't know exactly how.

class Ip(models.Model):
    customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE)
    ip = models.GenericIPAddressField(protocol="IPv4", null=False, unique=True)
    date_created = models.DateTimeField(auto_now_add=True,)
    date_updated = models.DateTimeField(auto_now=True,)
    date_assigned = models.DateTimeField(auto_now=True)

Any ideas? thanks in advance.

1 Answers

Please read the docs on overriding the save method.

One very useful tool for this is in the model_utils package.

from model_utils import FieldTracker

class Ip(models.Model):
    customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE)
    ip = models.GenericIPAddressField(protocol="IPv4", null=False, unique=True)
    date_created = models.DateTimeField(auto_now_add=True,)
    date_updated = models.DateTimeField(auto_now=True,)
    date_assigned = models.DateTimeField()

    customer_tracker = FieldTracker(fields=['customer'])

    def save(self, *args, **kwargs):
        if self.customer_tracker.changed():
            self.date_assigned = timezone.now()
        super().save(*args, **kwargs)
Related