Sobes.tech
Junior — Middle

Can you explain the role and operation of the pre_save method in Django?

sobes.tech AI

Answer from AI

In Django, there is no built-in method called pre_save, but there is a signal pre_save, which is called immediately before saving a model object to the database. This signal allows you to perform additional logic or validation before the data is written.

Example of using the pre_save signal:

from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(pre_save, sender=MyModel)
def mymodel_pre_save(sender, instance, **kwargs):
    # For example, automatically update a field before saving
    instance.updated_at = timezone.now()

Thus, pre_save helps control the save process and modify the object before writing it to the database.