【问题标题】:Sending notification to a specific type of user and save the notification in the database using django channels向特定类型的用户发送通知并使用 django 通道将通知保存在数据库中
【发布时间】:2021-11-06 15:20:16
【问题描述】:

我想向特定的用户组发送通知。假设特定组是管理员。当用户在管理员批准后在我的网站上注册时,该用户将被激活。需要通知此管理员。主要问题在于数据库设计。我需要保存通知。

class Notification(models.Model):
    view_name = models.CharField(max_length=255)
    notification_type = models.CharField(max_length=255)
    sender = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='notification_sender')
    recipient = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='notification_receiver')
    title = models.CharField(max_length=255)
    redirect_url = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_read = models.BooleanField(default=False)

这是模型。这里的 recipient 将是管理员。现在主要问题是会有超过 1 个管理员。如果我想保存通知,我想到的解决方案是遍历 User 模型找到管理员并发送每个管理员通知,这不是一个好的解决方案。 Django 频道文档显示有一种方法可以使用 gruop_send() 发送多个用户,是的,我可以使用它,但是如何将通知保存在具有多个收件人的数据库中?

【问题讨论】:

    标签: django database database-design django-channels


    【解决方案1】:

    您可以使用NotificationUser 之间的多对多关系将多个收件人关联到一个通知:

    class Notification(models.Model):
        view_name = models.CharField(max_length=255)
        notification_type = models.CharField(max_length=255)
        sender = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='notification_sender')
        recipients = models.ManyToManyField(User, related_name='notification_receivers')
        title = models.CharField(max_length=255)
        redirect_url = models.CharField(max_length=255)
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
        is_read = models.BooleanField(default=False)
    

    然后访问收件人:

    notification = Notification.objects.get(id=1)
    recipients = notification.recipients.all()
    

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多