Django post_migrate 信号被多次调用

Django post_migrate signal been called multiple times

我创建了一个 post_migrate,目的是在迁移 运行 时同步 table 中的所有数据。这是 post_migrate 文件的片段:

# signals.py
@receiver(post_migrate)
def full_sync_if_model_change(plan, **kwargs):
    if plan:
        models_set = set()
        for file, _ in plan:
            for model in file.operations:
                try:
                    model = SyncModel.objects.get(
                        app_name=file.app_label, model_name=model.model_name
                    )
                    models_set.add(model)
                except ObjectDoesNotExist:
                    pass
        print(models_set)
        if models_set:
            for model in models_set:
                model.set_full_sync()
                run_update_sync(model, False)
        return

但是,当我运行一次迁移时,调用了6次;正如您在迁移输出中看到的那样:

evandro@evandro-340XAA-350XAA-550XAA:~/Desktop/.../test_service$ python3 manage.py migrateOperations to perform:
  Apply all migrations: admin, auth, contenttypes, django_cron, lakehouse_sync, sessions, test_models
Running migrations:
  Applying test_models.0019_auto_20211026_2052... OK
set()
set()
set()
set()
set()
set()

我还将在此处添加应用程序文件:

class LakeSyncConfig(AppConfig):
    name = "lake_sync"

    def ready(self):
        """Import signals"""
        import lakehouse_sync.core.delete_action

        from . import signals

我不知道该怎么做,我尝试添加这个 return 语句,但是它不起作用,因为该函数一直在调用。

每个迁移的应用程序都会发送一次 post_migrate 信号,即使没有任何更改也是如此。当您的信号连接到仅 运行 您的函数时传递 sender 参数当您的应用已迁移时

def full_sync_if_model_change(plan, **kwargs):
    ...


class LakeSyncConfig(AppConfig):
    name = "lake_sync"

    def ready(self):
        post_migrate.connect(full_sync_if_model_change, sender=self)