django - 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)
解决方案
推荐阅读
- php - 如果用户试图访问网站 scouce 代码,如何阻止用户 ip
- ansible - ansible 在它注册变量的任务处停止
- html - 如何从 html 文件中调用存储过程
- php - Symfony Validator 看不到从 Doctrine 加载的实体的属性值
- python - Python:如何从列表中获取所有有序选项
- maven - 有什么方法可以在故障安全下并行运行 JUnit 5 集成测试?
- django - Django:TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“属性”
- filemaker - 在更改表格之前,对保存日期的引用不显示任何内容
- java - 将 HTML 解析为纯文本,但保留每个字符的标签信息
- python - PCL 安装错误