Search code examples
djangodjango-modelsdjango-signals

How do I use Django signals with an abstract model?


I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well.

If I connect the signal specifying the abstract model, this does not propagate to the derived models:

pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False)

If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once.

Where should I connect the signal?


Solution

  • Create a custom manager for your model. In its contribute_to_classmethod, have it set a signal for class_prepared. This signal calls a function which binds more signals to the model.