How to detect field changes in Django
The Problem While working on Django project, we have every now and then needed to know if a specific field of model has changed or not, and act accordingly. Let’s say, you are developing a logistics website, and want to store status changes of packages whenever there is one. So, you would have model structure similar to something like this:
from django.contrib.auth import get_user_model from django.db import models UserModel = get_user_model() class Status(models.Model): name = models.CharField(max_length=32, unique=True) class Package(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) shipment_cost = models.DecimalField(max_digits=6, decimal_places=2) weight = models.DecimalField(max_digits=5, decimal_places=2) status = models.ForeignKey(Status, on_delete=models.CASCADE) class PackageStatusHistory(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE) from_status = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='from_status', null=True) to_status = models.ForeignKey(Status, on_delete=models.CASCADE, related_name='to_status') created_at = models.DateTimeField(auto_now_add=True) Then, one would add post_save signals, and register the status change: