【问题标题】:How to implement simple notifications in drf + react?如何在 drf + react 中实现简单的通知?
【发布时间】:2022-01-20 06:42:56
【问题描述】:

通常在带有模板的 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) 中,这种任务的首选方式是什么。 我应该制作一个获取 api 来列出通知,而不是上下文处理器 并在响应前端的每个请求上调用此 api ?

【问题讨论】:

  • 你应该添加一些细节。您需要多久更新一次通知列表?最多有多少用户会同时使用该应用程序?您是否需要在前端应用发生某些事件后立即更新通知?你这里没有实现任何分页逻辑,为什么?
  • @YevgeniyKosmak 我需要在后端创建一些通知对象后立即在前端显示通知(延迟 2-3 分钟没问题)。
  • 其他问题呢? :)

标签: reactjs django django-rest-framework


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我应该创建一个 get api 来列出通知,而不是上下文处理器

    是的。您可以像这样创建 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()),
    

    并在响应前端的每个请求上调用此 api ?

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

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

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      相关资源
      最近更新 更多