You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django REST Framework中实现查看通知详情时标记已读功能

Django通知详情页自动标记已读实现

要实现在查看通知详情时自动将is_read字段设为True,只需重写NotificationDetailView的对应方法即可,以下是两种可行方案:

方案一:重写retrieve方法

class NotificationDetailView(generics.RetrieveUpdateAPIView):
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer

    def retrieve(self, request, *args, **kwargs):
        # 获取当前通知实例
        instance = self.get_object()
        # 仅当未读时标记为已读,减少不必要的数据库操作
        if not instance.is_read:
            instance.is_read = True
            # 指定只更新is_read字段,提升数据库操作性能
            instance.save(update_fields=['is_read'])
        # 调用父类方法完成正常的详情返回逻辑
        return super().retrieve(request, *args, **kwargs)

方案二:重写get_object方法

class NotificationDetailView(generics.RetrieveUpdateAPIView):
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer

    def get_object(self):
        instance = super().get_object()
        if not instance.is_read:
            instance.is_read = True
            instance.save(update_fields=['is_read'])
        return instance

说明

  • 两种方案核心逻辑一致:获取通知实例后,检查is_read状态,仅当未读时更新为已读状态
  • 使用update_fields=['is_read']可以让数据库仅更新目标字段,避免全字段更新,提升操作效率

内容的提问来源于stack exchange,提问作者Nayem Jaman Tusher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 11:19:57