如何引用models.py之外的信号

时间:2021-03-16 07:34:13

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

在Django的文档中,它指定models.py是一个定位信号回调函数的好地方(post_save,pre_save等)。

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.

您可以将信号处理和注册码放在任何您喜欢的地方。但是,您需要确保它所在的模块在早期导入,以便在需要发送任何信号之前注册信号处理。这使您的应用程序的models.py成为放置信号处理程序注册的好地方。

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)

2 个解决方案

#1


7  

How about "connecting" signals in models.py while keeping the functions in signals.py?

如何在models.py中“连接”信号,同时保持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

这样你就不必在信号中导入模型了

#2


1  

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

另一种选择是在__init__.py文件中导入信号。

This would have ensured early registration and avoided circular imports.

这将确保提前注册并避免循环进口。

#1


7  

How about "connecting" signals in models.py while keeping the functions in signals.py?

如何在models.py中“连接”信号,同时保持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

这样你就不必在信号中导入模型了

#2


1  

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

另一种选择是在__init__.py文件中导入信号。

This would have ensured early registration and avoided circular imports.

这将确保提前注册并避免循环进口。