如何从django捕获创建db信号

时间:2022-10-28 10:52:23

I'm working in django project. I have 1 postgresql sql file that need to run only one time after db created. Built-in django signal not quite suit with my case. So I try to write custom django signal but I'm not sure how to start with this case. Does anyone has a good guide. ? :)

我在django项目工作。我有1个postgresql sql文件,需要在db创建后只运行一次。内置的django信号不太适合我的情况。所以我尝试编写自定义django信号,但我不知道如何从这个案例开始。有没有人有一个很好的指导。 ? :)

1 个解决方案

#1


1  

The Django docs on signals have improved dramatically, so take a look there if you haven't already. The process is pretty simple.

关于信号的Django文档已经有了很大的改进,所以如果你还没有,请看看那里。这个过程非常简单。

First create your signal (providing_args lets you specify the arguments that will get passed when you send your signal later):

首先创建您的信号(provide_args允许您指定稍后发送信号时将传递的参数):

import django.dispatch
my_signal = django.dispatch.Signal(providing_args=["first_arg", "second_arg"])

Second, create a receiver function:

二,创建接收函数:

from django.dispatch import receiver

@receiver(my_signal)
def my_callback(sender, first_arg, second_arg, **kwargs):
    # do something

Finally, send your signal wherever you like in your code (self as sender is only applicable within your model class. Otherwise, just pass a the model class name):

最后,在您的代码中将您的信号发送到您喜欢的任何位置(发送者自己仅适用于您的模型类。否则,只需传递模型类名称):

my_signal.send(sender=self, first_arg='foo', second_arg='bar')

#1


1  

The Django docs on signals have improved dramatically, so take a look there if you haven't already. The process is pretty simple.

关于信号的Django文档已经有了很大的改进,所以如果你还没有,请看看那里。这个过程非常简单。

First create your signal (providing_args lets you specify the arguments that will get passed when you send your signal later):

首先创建您的信号(provide_args允许您指定稍后发送信号时将传递的参数):

import django.dispatch
my_signal = django.dispatch.Signal(providing_args=["first_arg", "second_arg"])

Second, create a receiver function:

二,创建接收函数:

from django.dispatch import receiver

@receiver(my_signal)
def my_callback(sender, first_arg, second_arg, **kwargs):
    # do something

Finally, send your signal wherever you like in your code (self as sender is only applicable within your model class. Otherwise, just pass a the model class name):

最后,在您的代码中将您的信号发送到您喜欢的任何位置(发送者自己仅适用于您的模型类。否则,只需传递模型类名称):

my_signal.send(sender=self, first_arg='foo', second_arg='bar')