如何只运行一次django信号,以便影响多个模型实例



是否可以只运行一次django信号以影响多个模型实例?这个信号什么时候会发出呢?我不想使用crontab库。

假设我有10个模型A的实例。我想运行一个信号,为模型a的每个实例创建一个模型B的实例

类似于下面的函数,但适用于所有A实例:

@receiver(signals.post_save, sender=A) 
def create_b(sender, instance, created, **kwargs):
if created:
B.objects.create()

你需要的是数据迁移。

首次运行:

python manage.py makemigrations --empty yourappname

这将在你的应用程序中生成一个空的迁移(这里是你的appname),你可以参考上面链接的文档,看看它会是什么样子。现在,您可以将自己的代码添加到迁移中,以执行您想要的操作。首先,您将添加一个函数,它将为您完成任务,并通过使用RunPython将其添加到列表operations。最后,您的迁移应该看起来像这样:

from django.db import migrations
def your_function(apps, schema_editor):
# We can't import the models directly as it may be a newer
# version than this migration expects. We use the historical version.
A = apps.get_model('yourappname', 'A')
B = apps.get_model('yourappname', 'B')
for a in A.objects.all():
b = B.objects.create()
# Do something with b if needed

class Migration(migrations.Migration):
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
migrations.RunPython(your_function),
]

现在任何运行python manage.py migrate的人都将运行此命令并了解您希望他们所做的更改。

最新更新