Search code examples
djangodjango-signals

What are the typical use cases for pre-save, post-save, pre-delete, post-delete signals in Django?


Could not find much in the docs here regarding use cases. However, I assume something along these lines:

  • Pre-Save: Used for calculated fields, example, we might want to calculate the age from date of birth and save that in the database.
  • Post-Save: Used for operations that involve other objects in the database, for example, updating a review might require a re-calculation of the average rating for the movie.
  • Pre-Delete: Honestly, no idea.
  • Post-Delete: Probably similar to post-save, in that it affects other models.

What are the most common use cases for these signals in general? Thanks.


Solution

  • A very common use for pre_save is slugifying titles, e.g. on books, articles, or products. This is also one reason it's always better to keep a separate ID to key on in URLs, etc. rather than relying solely on slugs, otherwise you either can't change your slugs or need to work around the fact that persistent pages may not have persistent URLs, or have to support legacy URLs/redirects.

    post_save may also be used for firing off or enqueuing asynchronous events; if you keep your users synced with a separate service, for example, a successful change to the local user profile may need to be submitted to an API, an operation you wouldn't want to make the user wait for. This kind of thing could technically be done elsewhere, but putting it in this signal means you don't have to worry about implementing or invoking it anywhere else.

    pre_delete can be used as a sanity check if you have objects that are shared in some way that wouldn't be caught by the more restrictive on_delete arguments. For example, if a teacher should only be allowed to delete a student object if that object has no associated attendance records, this could be one place to enforce that.

    post_delete, aside from things like statistical recalculations, can be used to alert admins or moderators to important user behavior. If a subscriber deletes an active payment method, in addition to deactivating that payment method on the payment processor, this signal could trigger an email to the relevant salesperson that they're in imminent danger of churn.

    When you get to signals, I'd say you're moving slightly out of the simple CRUD infrastructure that's probably Django's most common use case. So it's hard to point to the "most common use cases," as signals tend to become more useful as your project becomes more specialized.

    They're convenient when you need them, but personally, I only end up using them a few times a year; they're not something I'd suggest jumping for as a first option. Many or most things you'll need to do with Django can be done more simply and readably in, for example, an overridden save(...) method.