Junior — Middle
How is data saving preferably implemented: through overriding the save method or using signals?
sobes.tech AI
Answer from AI
It is preferable to override the save method if you need to change or extend the logic of saving a specific model, as this is more explicit and locally controls the save process.
Signals (e.g., in Django) are useful for separating side effects from the core model logic, such as sending notifications or updating related data without modifying the model itself.
If the task is to change data saving behavior, it is better to override save. If you need to react to a save event without interfering with the model, signals are more appropriate.
Example of overriding save:
class MyModel(models.Model):
name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
self.name = self.name.upper() # for example, always save name in uppercase
super().save(*args, **kwargs)
Example of using a signal:
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=MyModel)
def after_save(sender, instance, **kwargs):
print(f'Object {instance} has been saved')