Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference signals outside of models.py

Tags:

python

django

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)
like image 607
Brandon Bertelsen Avatar asked Dec 28 '12 00:12

Brandon Bertelsen


People also ask

How do you call a signal in Django?

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() .

Where is Pre_save signal in Django?

pre_save. This is sent at the beginning of a model's save() method. Arguments sent with this signal: sender.

What is Post_save in Django?

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.

What is the use of the Post_delete signal in Django?

To notify another part of the application after the delete event of an object happens, you can use the post_delete signal.


2 Answers

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

like image 161
migajek Avatar answered Nov 07 '22 21:11

migajek


Another option would have been to import signals in your __init__.py file.

This would have ensured early registration and avoided circular imports.

like image 42
Colleen Avatar answered Nov 07 '22 21:11

Colleen