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
  • Posts
  • Introduction
  • DSA
    • CodeForces
      • 1918-A: Brick Wall
    • ICPC
      • 2023
        • Azerbaijani
          • Classify The Roman Numerals
        • Nordic
          • Karl Coder
    • LeetCode
      • 2: Add Two numbers
      • 58: Length of Last Word
      • 142: Linked List Cycle II
    • Eolymp
      • 87: Robot
      • 325: Dangerous route
      • 4036 & 4038: Pre-Order/Post-Order Traversal of a Tree
      • 6254: Timebomb
    • HackerRank
      • Queen's Attack II
      • Winning Lottery Ticket
      • Balanced Brackets
  • Django
    • How to detect field changes in Django
  • Reinventing the wheel
    • Linux command: `ls`
      • Command, file types and flags
      • Starting with C
      • Getting the list of files and their info
      • Processing flags
      • Sorting and formatting the output
  • Open Source Projects
    • Integrify
  • Misc
    • How did I get into programming?
    • How I got job in two hours
  • Podcast Notes
    • The Diary of A CEO
      • Vinh Giang
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