我使用django信号的目的是在任何作者创建新博客文章时通知每个管理员。所以我想使用所有的管理员作为接收者,唯一创建博客文章的作者将是发送者。目前,我正在为set接收器特定的管理员用户使用此User.objects.get(username='jhone' )#jhone is an admin user
查询集。如何调用所有管理员用户并使主题全部作为接收者。这是我的代码:
#models.py
#using notifications model for signals
class Notifications(models.Model):
blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE)
blogcomment = models.ForeignKey('blog.BlogComment',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'))
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")
#others fields......
class Blog(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE,max_length=100)
#others fields....
def blog_notify(sender, instance, *args, **kwargs):
blog = instance
blog_title = blog.title
sender = blog.author
receiver = User.objects.get(username='jhone')
if sender == blog.author and blog.is_published == "published":
notify = Notifications(blog=blog, sender=sender,receiver =receiver ,text_preview = blog_title[:250], notification_type="post approved")
notify.save()
post_save.connect(Blog.blog_notify, sender=Blog)
我还尝试了一些queryset,将所有管理员用户设置为接收者,但主题无关。
receiver = User.objects.all().filter(is_superuser=True)
我得到这个错误:
Cannot assign "<QuerySet [<User: Jhone>, <User: admin1>, <User: admin2>]>": "Notifications.user" must be a "User" instance.
用于使用此查询集的CCD_ 2。
我也试过这个
receiver = User.objects.all().get(is_superuser=True)
并且得到这个错误
MultipleObjectsReturned at /blog-admin/approve-blog-post/tusar-post2/
get() returned more than one User -- it returned 3!
知道如何传递正确的queryset以将所有管理员用户设置为接收者吗???
您需要遍历所有管理员,并逐个创建Notifications
,如下所示:
def blog_notify(sender, instance, *args, **kwargs):
blog = instance
blog_title = blog.title
sender = blog.author
receivers = User.objects.filter(is_superuser=True)
if not (sender == blog.author and blog.is_published == "published"):
return
notifications = []
for receiver in receivers:
notifications.append(Notifications(blog=blog, sender=sender, receiver=receiver, text_preview=blog_title[:250], notification_type="post approved"))
Notifications.objects.bulk_create(notifications)
请注意,如果Notifications
模型正在发送信号,则不能使用bulk_create
。在这种情况下,只需逐个创建它们。