Open In App

Overriding the save method - Django Models

Last Updated : 17 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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". 

django-models-overriding-save-method

Let us check what we have created in admin interface. 

django-overriding-save-method

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.


Next Article
Practice Tags :

Similar Reads