django updated_at field

  1. Open your Django model file.
from django.db import models

class YourModel(models.Model):
    # Your existing fields here

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
  1. Make sure to run makemigrations and migrate commands to apply the changes to your database.
python manage.py makemigrations
python manage.py migrate
  1. In your views or serializers, update the logic to save the updated_at field when your model instance is updated.
from django.utils import timezone

# Inside your view or serializer logic where you update the model instance
your_model_instance.updated_at = timezone.now()
your_model_instance.save()
  1. Optionally, if you want to display the updated_at field in the Django admin panel, update your model's admin.py file.
from django.contrib import admin
from .models import YourModel

@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
    list_display = ('id', 'created_at', 'updated_at',)  # Add 'updated_at' to the list display
  1. Run your Django development server and check the Django admin panel or your application to ensure that the updated_at field is being updated correctly.
python manage.py runserver

Now, your Django model has an updated_at field that automatically updates whenever the model instance is modified.