首页 > 解决方案 > Djngo Signals 如何在查询集中找到重复项并将它们指定为发送方和接收方?

问题描述

我在我的BlogComment 模型中使用 django post_save 信号并创建每个对象的副本。我想为我的发件人指定第一个副本,为我的接收者指定第二个副本。如何在查询集中做到这一点?

我的发件人的这个查询集:

notifications = Notifications.objects.all().filter(sender=user).order_by('-date')

我的接收者的这个查询集:

notifications = Notifications.objects.all().filter(receiver=user).order_by('-date')

这是我的BlogComment模型,它创建了 Notifications 对象:

class BlogComment(models.Model):
      blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True)
      #my others fileds
      #here signals stating 
      def user_comment(sender, instance, *args, **kwargs):
            comment= instance
            blog = comment.blog
            sender = comment.user
            commnet_notes = comment.rejected_comment_notes
            comment_text = comment.comment
            
            if sender != blog.author and comment.is_published == "pending":
               notify = Notifications(blog=blog, sender=sender, receiver=comment.blog.author,text_preview=comment_text[:250], notification_type="New Comment")
               notify.save() #want appoint this object for receiver in queryset
               notify2 =Notifications.objects.create(blog=blog, sender=sender, receiver=comment.blog.author, text_preview=comment_text[:250], notification_type="New Comment")
               notify2.save() #want appoint this object for sender in queryset
   
post_save.connect(BlogComment.user_comment, sender=BlogComment) 

这是我的通知模型

class Notifications(models.Model):
    blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE,blank=True,null=True)
    blogcomment = models.ForeignKey('blog.BlogComment',on_delete=models.CASCADE, blank=True,null=True)
    globalnotifications = models.ForeignKey('blog.GlobalNotifications',on_delete=models.CASCADE,blank=True,null=True)
    NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected'),('pending post','pending post'),('post approved','post approved'),('post rejected','post rejected'),('global_noti','global_noti'))
    sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user")
    receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user")
    notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250,default="New Comment")
    text_preview = models.CharField(max_length=500, blank=True)
    help_notes = models.TextField(max_length=1000,default="",blank=True,null=True)
    date = models.DateTimeField(auto_now_add=True)
    is_seen = models.BooleanField(default=False)
    is_seen_author_noti = models.BooleanField(default=False)

    def __str__(self):
          return str(self.notification_type)

标签: django

解决方案


推荐阅读