0

我创建的django应用程序会在创建某个模型时通过websocket发送消息。模型在django-rest-framework中完成保存时的信号

我的模型看起来是这样的:

class Notification(model.Model): 
    owner = models.ForeignKey(User) 
    datetime = models.DateTimeField(auto_now_add=True) 
    resources = models.ManyToManyField(Resource, related_name='notifications', blank=True) 
    recipients = models.ManyToManyField(User, related_name='notifications', blank=True) 

我想,当模型完成后保存到发送信号。如果我使用m2m_changed信号,那么如果m2m字段留空,则不会调用信号。即使字段不为空,我也需要将m2m_changed绑定到两个关系,这会导致通过websocket发送多个消息。如果我使用post_save,则post_save接收器内m2m_field为空。

还有其他的选择吗?

我试过编写自定义信号,但我不是django的专家,我不知道如何知道模型何时完成保存。

谢谢

+0

可能['on_commit'](https://docs.djangoproject.com/en/1.10/topics/db/transactions/#performing-actions-after-commit)可能对此有帮助。 –

+0

但是在数据库的每次写入时都会调用这个函数,并且在回调函数中也没有参数,至少会告诉我哪个对象正在保存。 –

+0

在保存后,你是否尝试访问实例变量?它必须包含M2M变量! –

回答

0

书写模型信号不是先进/困难。请点击这里docs。覆盖模型的保存功能以发送您的自定义信号。

# in Notification class 
def save(self, *args, **kwargs): 
    super(Notification, self).save(*args, **kwargs) 
    # model and m2m fields are updated now 
    my_signal.send(*some_args, **some_kwargs) 

希望它有帮助!

相关问题