Overriding the save method in Django

Last updated 1 year, 4 months ago | 914 views 75     5

Tags:- Django

Django | Overriding the save method

The save method is inherited from models.Model class. It is used to override the save method before storing the data in the database. This is used when there is a need to modify or update the data which is going to insert in the database.

Let's create a Post model having the following fields:  title, slug, description, seo_title, seo_description, seo_keywords

from django.db import models  
from django.utils.text import slugify  
# Create Post models 
class Post(models.Model): 
    title = models.CharField(max_length = 200)
	description = models.TextField()
    slug = models.SlugField()
	seo_title = models.CharField(max_length = 200, null = True, blank = True)
	seo_keywords = models.CharField(max_length = 200, null = True, blank = True)
	seo_description = models.CharField(max_length = 200, null = True, blank = True)

	# overridden Save method
	def save(self, *args, **kwargs):
		# slugify title
		self.slug = slugify(self.title)
		# check seo_title and seo_keywords for None and assign title field's value
        if self.seo_title is None:
            self.seo_title = self.title
        if self.seo_keywords is None:
            self.seo_keywords = self.title
		# Check seo_description for None and assign first 30 words from description field
		if self.seo_description is None:
            self.seo_description = ' '.join(self.description.split()[:30])
		super(Post, self).save(*args, **kwargs)

In the above code, the save method is used to provide values for the slug, seo_title, seo_keywords, and seo_description fields.