首页 > 解决方案 > 在 django 信号中使用多个实例和发件人

问题描述

我如何在 django 信号中使用多个实例和发送者(不同的模型)。

receiver(post_save, sender=Comment)
@receiver(post_save, sender=Post)
def create_comment_notification(*args, **kwargs):
    #comments  notifier
    comment = kwargs['instance']
    post = kwargs['instance']
    if kwargs['created']:
        if comment.author != comment.post_connected:
            Notification.objects.create(
                assigned_to = post.author,
                group='NC',
                body=f"{comment.author} commented: {comment.content} on your post.",
                pk_relation=comment.id
            )
    else:
        if comment.author != comment.post_connected:
            Notification.objects.create(
                assigned_to = post.author,
                group='NC',
                body=f"{comment.author} commented: {comment.content}.",
                pk_relation=comment.id
            )

我注意到它可以工作,但不能识别 POST 模型,它只使用 COMMENT。我如何将这两个模型用作发件人。并让代码分别识别它们。

谢谢

标签: djangodjango-signals

解决方案


推荐阅读