Django如何查询所有管理员用户并在信号中作为通知接收者
问题解决方法
错误原因
你当前遇到报错的核心原因是:
Notifications模型中的receiver字段是单用户外键,每条通知记录只能绑定1个用户实例User.objects.get()仅能返回单个用户实例,存在多个匹配结果时就会抛出MultipleObjectsReturned错误User.objects.filter()返回的是用户查询集(QuerySet),无法直接赋值给要求接收单用户实例的receiver字段
正确实现方式
你只需要遍历所有超级用户,为每个管理员单独创建一条通知记录即可,修改后的blog_notify方法代码如下:
def blog_notify(sender, instance, *args, **kwargs): blog = instance # 避免重复触发通知(只有文章首次发布为已发布状态时才发通知) if kwargs.get('created', False) and blog.is_published == "published": blog_title = blog.title sender_user = blog.author # 获取所有超级管理员用户 admins = User.objects.filter(is_superuser=True) # 遍历为每个管理员创建通知 notify_list = [] for admin in admins: # 跳过给作者本人发通知(可选,根据需求调整) if admin == sender_user: continue notify_list.append(Notifications( blog=blog, sender=sender_user, receiver=admin, text_preview=blog_title[:250], notification_type="post approved" )) # 批量创建通知,减少数据库IO次数 if notify_list: Notifications.objects.bulk_create(notify_list)
优化说明
- 新增
kwargs.get('created', False)判断,只有首次创建文章时才触发通知,避免后续编辑文章重复推送 - 新增跳过作者本人的逻辑,避免给自己发通知,不需要可以删除
- 使用
bulk_create批量插入通知记录,相比循环调用save()能大幅减少数据库请求次数,性能更好
内容的提问来源于stack exchange,提问作者boyenec
相关产品推荐
相关产品推荐

