每當用戶喜歡帖子時,我都會嘗試創建通知。為此,我正在使用 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'>
我究竟做錯了什么?我是否需要參考中間類 Post_liked_by,如果需要,我該怎么做?
uj5u.com熱心網友回復:
您應該指定through模型的ManyToManyField模型,所以Post.liked_by.through,不是Post:否則不清楚ManyToManyField您正在訂閱什么。因此,我們將處理程式定義為:
#core/signals.py
@receiver(m2m_changed, sender=Post.liked_by.through)
def likeNotification(sender,**kwargs):
# …
您可以通過以下方式提高效率以確定喜歡的數量:
#socialuser/models.py
class Post(Authorable, Creatable, Model):
# …
def no_of_likes(self):
return self.liked_by.count()
然后它將在資料庫端確定點贊數,從而減少從資料庫到 Django/Python 應用層的帶寬。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/418252.html
標籤:
上一篇:如何從元組串列中僅提取數字
