如何在 drf + react 中实现简单的通知?

How to implement simple notifications in drf + react?

通常在带有模板的 django 中,我会像这样实现基本通知。

例如

class Article(models.Model):
   name = models.CharField()
   owner = models.ForeignKey(User)
   
class Comment():
   article = models.ForeignKey(Article)
   txt = models.CharField()
   user = models.ForeginKey()
   datetime = models.DateTimeField(auto_now_add=True)
  
class ArticleNotification():
    article = models.ForeignKey(Article)
    msg = models.CharField()
    is_seen = models.BooleanField(default=False)
    datetime = models.DateTimeField(auto_now_add=True)
    

如果有人对文章发表评论,所有者将看到通知。

   @transaction.atomic
   def post_comment(request, article_id):
      comment = Comment.objects.create(article_id=article_id, txt="Nice Article", user=request.user)
      ArticleNotification.objects.create(article_id=article_id, msg=f"User {request.user} commented on your post")

现在显示我通常制作上下文处理器的通知:

# context_processor:
def notifcations(request):
    notifs = Notfication.objects.filter(article__owner=request.user).order_by("-datetime")
    return {"notifs":notifs}

这样我就可以正常实现带刷新的基本通知系统了

现在在 (drf + react) 中,这种类型的任务的首选方式是什么。 我应该使用 get api 来代替上下文处理器来列出通知 并在来自 React 前端的每个请求中调用此 api ?

Instead of context processor should I have to make an get api to list notifications

是的。您可以像这样创建 DRF API 视图

serializers.py

class ArticleNotificationSerializer(ModelSerializer):
    class Meta:
        model = ArticleNotification
        fields = ["id", "article", "msg", "is_seen", "datetime"]

views.py

class ArticleNotificationListView(ListAPIView):
    serializer_class = ArticleNotificationSerializer
    queryset = ArticleNotification.objects.all()

urls.py

path('notification', ArticleNotificationListView.as_view()),

And call this api on every request from react frontend ?

是的。您还可以在反应组件中使用 setInterval and componentDidMount hook 每 10 秒检查一次通知。

componentDidMount: function() {
    this.countdown = setInterval(function() {
        axios.get(
           '/notifications/'
        ).then(r => 
            this.setState({ notifications: r.data }); // Changing state
        )
    }, 10000);
},

对于实时通知,您需要像 Django 通道之类的东西,或者您可以设置一个 get api from react,它在每个定义的时间(比如 5 分钟)后运行,并根据用户获取所需的通知.

在您的情况下,上下文处理器中的内容将在列表api视图中,稍后您可以获取所有列表。