Logo Miradil's Blog
  • Home
  • About
  • Skills
  • Experiences
  • Education
  • More
    Projects Publications Recent Posts
  • Posts
  • Dark Theme
    Light Theme Dark Theme System Theme
Logo Inverted Logo
  • Tags
  • Backend
  • Basic
  • Binary Search Tree
  • BinarySearch
  • Bit Manipulation
  • C
  • Caching
  • Codeforces
  • Disjoint Set
  • Django
  • DSA
  • Easy
  • Eolymp
  • File Structure
  • File System
  • ForBeginners
  • Formatted I/O
  • HackerRank
  • HowTo
  • ICPC
  • Interactive
  • Interview
  • Intro
  • Leetcode
  • Library Functions
  • LinkedList
  • Linux
  • Medium
  • Open Source
  • Podcasts
  • Programming
  • Public Speaking
  • Python
  • Roadmap
  • Stack
  • System Calls
  • The Diary of a CEO
  • Tricky
  • Vinh Giang
  • Web Development
Hero Image
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:

Wednesday, November 8, 2023 | 6 minutes Read
Navigation
  • About
  • Skills
  • Experiences
  • Education
  • Projects
  • Publications
  • Recent Posts
Contact me:
  • miradil.zeynalli@gmail.com
  • mmzeynalli
  • Miradil Zeynalli
  • @mmzeynalli
  • Miradil Zeynalli
  • @mmzeynalli

Toha Theme Logo Toha
© 2024 Copyright.
Powered by Hugo Logo