如何引用models.py以外的信号 [英] How to reference signals outside of models.py

查看:113
本文介绍了如何引用models.py以外的信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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)


推荐答案

如何将models.py中的连接信号保留在signals.py中?

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

一个例子:

# 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 

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

这篇关于如何引用models.py以外的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆