model.py and signal.py in django

models.py and signals.py in each app have been the recommended places to connect signals, however, they are not the best solution, in my opinion, to keep signals and handlers dispatched. Dispatching should be the reason signals and handlers invented in django.
I was struggling for long time, and finally we figured out the solution.

create a connector module in app folder
so we have:
app/
    __init__.py
    signals.py
    models.py
    connectors.py
in app/connectors.py, we defined signal handlers and connect them.

An example is provided:
from signals import example_signal
from models import ExampleModel
from django.db.models.signals import post_save, post_delete

def hanndler(sender, *args, **kwargs):
    pass

post_save.connect(hander, sender=ExampleModel)

then in models.py, we add the following line in the end of the file:
 
 
from app import connector

Everything done here.
In this way, we can put signals in signals.py, and all the handlers in connectors.py. No mess in models and signals.

No comments:

Post a Comment