Overriding the save method in Django

Last updated 3 years, 3 months ago | 1583 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.
 

Tips and Tricks


Python In-place swapping of two numbers

 Python | In-place swapping of two numbers

>>> a, b = 10, 20
>>> print(a, b)
10 20

>>> a, b = b, a
>>> print(a, b)
20 10

 


Reversing a String in Python

Python | Reversing a String

>>> x = 'PythonWorld'
>>> print(x[: : -1])
dlroWnohtyP

 


Python join all items of a list to convert into a single string

Python | Join all items of a list to convert into a single string

>>> x = ["Python", "Online", "Training"]
>>> print(" ".join(x))
Python Online Training

 


python return multiple values from functions

Python | Return multiple values from functions

>>> def A():
	return 2, 3, 4

>>> a, b, c = A()

>>> print(a, b, c)
2 3 4

 


Python Print String N times

Python | Print String N times

>>> s = 'Python'
>>> n = 5

>>> print(s * n)
PythonPythonPythonPythonPython