Django Signals VS. Overriding Save Method

Django signals vs. overriding save method

Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models.

One common task in overridden save methods is automated generation of slugs from some text field in a model. That's an example of something which, if you needed to implement it for a number of models, would benefit from using a pre_save signal, where the signal handler could take the name of the slug field and the name of the field to generate the slug from. Once you have something like that in place, any enhanced functionality you put in place will also apply to all models - e.g. looking up the slug you're about to add for the type of model in question, to ensure uniqueness.

Reusable applications often benefit from the use of signals - if the functionality they provide can be applied to any model, they generally (unless it's unavoidable) won't want users to have to directly modify their models in order to benefit from it.

With django-mptt, for example, I used the pre_save signal to manage a set of fields which describe a tree structure for the model which is about to be created or updated and the pre_delete signal to remove tree structure details for the object being deleted and its entire sub-tree of objects before it and they are deleted. Due to the use of signals, users don't have to add or modify save or delete methods on their models to have this management done for them, they just have to let django-mptt know which models they want it to manage.

Background workers and overriding save method on Django models

One option is to use bulk_update to update instances in your background task. This function won't call the model's save method and won't emit any signals, eliminating any recursion problem.

To use signals or override model save method?

You cannot access the user object from a signal.
You can consider using this third party package: django-requestprovider to access the request object in the signal.

The other way would be to overriding the models' save method.

override the save method in django

You can try a signal like this:

from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.utils import timezone

@receiver(pre_save, sender=Product)
def update_create_field(sender, instance, **kwargs):
try:
_pre_save_instance = Product.objects.get(pk=instance.pk)
if _pre_save_instance.price != instance.price:
instance.create = timezone.now() #here you can specify any value you want
except Exception as e:
print('Error updating create field!')
print(e)


Related Topics



Leave a reply



Submit