python / beginner
Snippet
Customizing Model Save Logic
Overriding the save() method allows you to run custom code (like data validation or auto-filling fields) whenever an object is stored.
snippet.py
1
2
3
4
5
6
7
from django.db import modelsclass Profile(models.Model):def save(self, *args, **kwargs):# Custom logic before savingprint('Saving profile data...')super().save(*args, **kwargs)
django
Breakdown
1
def save(self, *args, **kwargs):
Defines the custom version of the model's save method.
2
super().save(*args, **kwargs)
Ensures the original saving process still happens by calling the parent class.