In the documentation for Django
, it specifies that models.py
is a good place to locate callback functions for signals (post_save
, pre_save
, etc).
Where should this code live?
You can put signal handling and registration code anywhere you like. However, you'll need to make sure that the module it's in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app's models.py a good place to put registration of signal handlers.
source: https://docs.djangoproject.com/en/dev/topics/signals/
However, I have a significant amount of business logic that relies on signals and it's becoming challenging to view them in the same file as all my models.
I would like to move them to another file, but I don't know how or where I can reference them.
So, given the following file structure, could you provide an example of how I can reference a secondary (or tertiary and so on) file that contains appropriate signals?
# models.py located in /myapp/some_installed_app/
from django import needed.modules
... # some reference to signals.py?
class SomeModel()
pass
# signals.py located in /myapp/some_installed_app/
from django import needed.things
...
def somefun(sender,**kwargs)
pass
post_save.connect(somefun, sender=SomeModel)
Sending signals There are two ways to send signals in Django. To send a signal, call either Signal. send() (all built-in signals use this) or Signal. send_robust() .
pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.
Tips to use post_save As the name suggests, it is called just after the Django model save() function has done its job. The sender parameter here defines the Model from which we are trying to receive the signal.
To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.
How about "connecting" signals in models.py while keeping the functions in signals.py?
an example:
# models
from myapp import signals
class MyModel(models.Model)
pass
post_save.connect(signals.do_some_stuff_with_mymodel, sender = MyModel)
# signals
def do_some_stuff_with_mymodel(**kwargs):
pass
that way you don't have to import models
in signals
at all
Another option would have been to import signals in your __init__.py
file.
This would have ensured early registration and avoided circular imports.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With