【问题标题】:Do I need to append dispatch_uid to signal in this case?在这种情况下,我是否需要附加 dispatch_uid 来发出信号?
【发布时间】:2018-01-04 06:36:22
【问题描述】:

在 Django 文档中,我读到:https://docs.djangoproject.com/en/2.0/topics/signals/#preventing-duplicate-signals

在某些情况下,将接收器连接到信号的代码可能 运行多次。这可能会导致您的接收器功能 注册了不止一次,因此一次调用了多次 信号事件。

那么,如果我使用信号作为,

class CustomauthConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        import myapp.signals

@receiver(post_save, sender=TestModel)
def update_log(sender, instance, **kwargs):
    TestModelLog.objects.create(description=instance.description, datetime=instance.updated)

问题:

我不需要dispatch_uid对吗?

或者如果我必须使用dispatch_uid,你能给我一个使用dispatch_uid的样本吗?

我的目的是防止重复

【问题讨论】:

    标签: django


    【解决方案1】:

    由于您使用create 一个新日志的信号(尽管您的函数名为update_log),因此您最好使用update_or_create() 方法:

    @receiver(post_save, sender=TestModel)
    def update_log(sender, instance, **kwargs):
        TestModelLog.objects.update_or_create(
            description=instance.description, datetime=instance.updated
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多