Django signals vs. overriding save method

PythonDjangoDjango ModelsDjango Signals

Python Problem Overview


I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:

 def Review(models.Model)
    ...fields...
    overall_score = models.FloatField(blank=True)

def Score(models.Model)
    review = models.ForeignKey(Review)
    question = models.TextField()
    grade = models.IntegerField()

A Review is has several "scores", the overall_score is the average of the scores. When a review or a score is saved, I need to recalculate the overall_score average. Right now I'm using a overridden save method. Would there be any benefits to using Django's signal dispatcher?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

You asked:

Would there be any benefits to using Django's signal dispatcher?

I found this in the django docs:

> Overridden model methods are not called on bulk operations > > Note that the delete() method for an object is not necessarily called > when deleting objects in bulk using a QuerySet or as a result of a > cascading delete. To ensure customized delete logic gets executed, you > can use pre_delete and/or post_delete signals. > > Unfortunately, there isn’t a workaround when creating or updating > objects in bulk, since none of save(), pre_save, and post_save are > called.

From: Overriding predefined model methods

Solution 3 - Python

Small addition from Django docs about bulk delete (.delete() method on QuerySet objects):

> Keep in mind that this will, whenever possible, be executed purely in > SQL, and so the delete() methods of individual object instances will > not necessarily be called during the process. If you’ve provided a > custom delete() method on a model class and want to ensure that it is > called, you will need to “manually” delete instances of that model > (e.g., by iterating over a QuerySet and calling delete() on each > object individually) rather than using the bulk delete() method of a > QuerySet.

https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects

And bulk update (.update() method on QuerySet objects):

> Finally, realize that update() does an update at the SQL level and, > thus, does not call any save() methods on your models, nor does it > emit the pre_save or post_save signals (which are a consequence of > calling Model.save()). If you want to update a bunch of records for a > model that has a custom save() method, loop over them and call save()

https://docs.djangoproject.com/en/2.1/ref/models/querysets/#update

Solution 4 - Python

If you'll use signals you'd be able to update Review score each time related score model gets saved. But if don't need such functionality i don't see any reason to put this into signal, that's pretty model-related stuff.

Solution 5 - Python

It is a kind sort of denormalisation. Look at this pretty solution. In-place composition field definition.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionimjoevasquezView Question on Stackoverflow
Solution 1 - PythonJonny BuchananView Answer on Stackoverflow
Solution 2 - PythonguettliView Answer on Stackoverflow
Solution 3 - PythonvalexView Answer on Stackoverflow
Solution 4 - PythonDmitry ShevchenkoView Answer on Stackoverflow
Solution 5 - PythonAlex KoshelevView Answer on Stackoverflow