Overriding the save method - Django Models
Last Updated :
17 May, 2025
The save method is an inherited method from models.Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run. We can override save function before storing the data in the database to apply some constraint or fill some ready only fields like SlugField.
Example of Django Overriding the Save Method
Illustration of overriding the save method using an example, consider a project named "geeksforgeeks" having an app named "geeks".
Refer to the following articles to check how to create a project and an app in Django.
Step 1: Define the Model in models.py
In your Django app (let’s assume it’s named geeks), open the models.py file and define a model like this:
Python
from django.db import models
from django.utils.text import slugify
class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(GeeksModel, self).save(*args, **kwargs)
In the code above:
- slugify(self.title): Converts the title into a URL-friendly string. This function replaces spaces with hyphens and converts the text to lowercase.
- if not self.slug: : This condition ensures that we only generate the slug when it’s not already set (to avoid overwriting an existing slug).
Step 2: Migrate the Changes
After modifying your model, you need to apply the changes to the database. Run the following commands to generate and apply the migration files:
1. Generate the migration files:
python manage.py makemigrations
2. Apply the migrations to the database:
python manage.py migrate
Let us try to create an instance with "Gfg is the best website".

Let us check what we have created in admin interface.

Advanced Concepts: Issues with Overriding the Save Method
While overriding the save() method works well for generating slugs or performing other custom logic, there are some caveats you need to be aware of:
1. Overwriting Existing Slugs: As mentioned earlier, the save() method will regenerate the slug every time the model is saved, even if only the title is updated. This can lead to issues, especially if the slug is already being used as part of the URL structure, such as in SEO contexts where changing the slug can break links and affect search engine rankings. To avoid changing the slug when only the title is updated, you can modify the logic to only generate the slug if it's empty:
Python
def save(self, *args, **kwargs):
if not self.slug: # Only generate slug if it's not already set
self.slug = slugify(self.title)
super().save(*args, **kwargs)
2. Preventing Errors: Overriding save() directly in the model can cause issues if not handled properly. If an exception occurs during the save process, it can interrupt the saving of data, causing an error. If you choose to override the save() method, ensure that you have proper error handling in place and avoid complex logic inside the method. Instead, consider using other mechanisms like Django forms, signals, or model methods for complex processing.
3. Database Integrity: It’s important to ensure that custom save logic does not inadvertently violate database constraints (e.g., uniqueness or foreign key relationships). In particular, automatic changes to fields such as slugs may conflict with unique constraints if not handled carefully. Always check for uniqueness manually or let Django handle it through database constraints, rather than relying solely on save() for enforcing uniqueness.
Similar Reads
Django Models A Django model is a Python class that represents a database table. Models make it easy to define and work with database tables using simple Python code. Instead of writing complex SQL queries, we use Djangoâs built-in ORM (Object Relational Mapper), which allows us to interact with the database in a
8 min read
Django ORM - Inserting, Updating & Deleting Data Django's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Django Basic App Model - Makemigrations and Migrate Django's Object-Relational Mapping (ORM) simplifies database interactions by mapping Python objects to database tables. One of the key features of Django's ORM is migrations, which allow you to manage changes to the database schema.What are Migrations in Django?Migrations are files that store instru
4 min read
Add the slug field inside Django Model The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing
4 min read
Intermediate fields in Django - Python Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship is used when instances of one model can be associated with multiple instances of another model and vice versa. For example, in a shop management system:A Customer can purchase multiple Items.An Item can be
2 min read
Uploading images in Django - Python Prerequisite - Introduction to DjangoUploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.In this article, weâll walk through a
3 min read
Customize Object Names with __str__ Method When you create instances of a Django model, by default, they appear in the Django admin interface and elsewhere as "ModelName object (1)" (or a similar format). This can make it hard to identify records, especially when you have many objects.Why Customize Object Display Names?By default, Django doe
2 min read
Custom Field Validations in Django Models Field validation ensures that the data entered into a model field meets specific rules before itâs saved to the database. While Django provides built-in validations for common checks, custom field validation lets you enforce your own rules, such as verifying formats, length limits, or complex condit
3 min read
Meta Class in Models - Django Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
How to use Django Field Choices ? Djangoâs choices option lets you limit a model field to a fixed set of values. It helps keep your data clean and consistent, and automatically shows a dropdown menu in forms and the admin instead of a text box.Choices are defined as pairs: the first value is saved to the database, and the second is
2 min read