编辑many_to_many字段时,在Django中避免重复信号

时间:2015-12-16 17:50:39

标签: python django django-models django-signals

我想自动更新有关模型更改的外部应用程序。问题是数据在事件< - > 用户之间存在许多关系。我试图使用"m2m_changed" signal

@receiver(m2m_changed, sender=models.Event.organisers.through)
def event_changed(sender, instance, action, *args, **kwargs):
    if "post" in action:
      # hey api here is the new list of organisers of this

这个问题是,如果我进行一次更改,我删除一个用户并添加另一个用户,那么这个代码会被调用两次!这不好,我可以'如果仅调用该操作,则忽略一种操作。我曾想过将实例推送到堆栈并忽略重复,但这看起来很混乱。有没有办法让我自己的信号只发射一次?

2 个答案:

答案 0 :(得分:1)

对于这个问题,没有中继似乎是一个很好的答案,所以这里有一些有用的解决方法比我在第一步中想象的更好。

解决方案1:

而不是组合信号而是将实例的主键添加到集合中以忽略重复信号:

updated = set()

@receiver(m2m_changed, sender=models.Event.organisers.through) 
def event_changed(sender, instance, action, *args, **kwargs):
        if "post" in action:
          updated.add(instance.pk)

def send_updates():
    for Event in updated:              # Iteration AKA for each element
       #update code here

虽然这需要某种计划任务来运行send_updates(),但如果事件有很多连续的更改,它可以避免发送垃圾邮件的可能性。

解决方案2

忽略信号完全将最后修改添加到模型中。然后运行查询以从现在到最后一次调用send_updates()之间获取所有事件。将最后调用的地方存储到磁盘/数据库,以避免在重新启动时重新发送所有内容。

答案 1 :(得分:1)

Django @M01790:39:000000000-C3C6P:1:1101:14141:1618 1:N:0:8 TATTCACATATAGACATGAAA #is the string that matched the regexp WITHOUT initial AA that doesn' match my expression ATATTCACATATAGACATGAAACACCTGTGGTTCTTCCTC #without initial AA + GGGFGGGGGGFGGGGGGGGGGGFGGGGFGFGFFGGGGFGF # without "GGGGGGGGDGGGFGGGGGGFGGG" that is the same number of characters removed in the 2nd line 表示对ManyToMany模型的更改。如果有4次操作

  1. pre_add
  2. post_add
  3. pre_remove
  4. post_remove

因此,如果您仅添加一个用户,则此m2m_changed方法将分别触发两次,分别为.ec-tabs>li.active, .wc-tabs>li.active { display: block; } .ec-tabs>li, .wc-tabs>li { display: none; } m2m_changed

您可以指定要调用API的操作。可以这样做:

pre_add

参考Django文档:https://docs.djangoproject.com/en/2.2/ref/signals/#m2m-changed