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) 

希望它有幫助!

相關問題