Django 信号接收器功能不接受发件人

Django Signal Receiver Function not accepting sender

我正在尝试在用户喜欢 post 时创建通知。为此,我正在使用 django 信号。我以前在接收者装饰器中使用过发送者争论,但不知道为什么这次不工作。这是我的文件。

#core.signals.py
@receiver(m2m_changed, sender=Post)
def likeNotification(sender,**kwargs):
    if kwargs['action'] == "post_add" and not kwargs['reverse']:
        post = kwargs['instance']
        to_user = post.user
        liked_by_users = kwargs['pk_set']
        like_notification = [Notification(
            post=post,
            user=to_user, sender=User.objects.get(id=user),
            text=f"{User.objects.get(id=user).profile.username} liked your post.", noti_type=3
        ) for user in liked_by_users]
        Notification.objects.bulk_create(like_notification)
#socialuser.models.py
class Post(Authorable, Creatable, Model):
    caption = TextField(max_length=350, null=True, blank=True)
    liked_by = ManyToManyField(
        "core.User", related_name="like_post", blank=True)

    objects = PostManager()

    def no_of_likes(self):
        return len(self.liked_by.all())

当 sender=Post 时,接收器未捕获信号,当我删除发送器时,它按预期工作。打印 likeNotification 函数的位置参数发送者。这就是我得到的

<class 'socialuser.models.Post_liked_by'>

我做错了什么?我是否需要参考中间 class Post_liked_by,如果需要我该怎么做?

你应该指定ManyToManyField型号的through型号,所以Post.liked_by.through,而不是Post:否则不清楚[=11] =] 您正在订阅。因此,我们将处理程序定义为:

#core/signals.py

@receiver(m2m_changed, sender=<strong>Post.liked_by.through</strong>)
def likeNotification(sender,**kwargs):
    # …

您可以通过以下方式提高确定点赞数的效率:

#socialuser/models.py

class Post(Authorable, Creatable, Model):
    # …

    def no_of_likes(self):
        return self.liked_by<b>.count()</b>

然后会在数据库端判断点赞数,从而减少数据库到Django/Python应用层的带宽。