51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
# apps/notification/views.py
|
|
from rest_framework import viewsets, status
|
|
from rest_framework.permissions import IsAuthenticated
|
|
from rest_framework.response import Response
|
|
from rest_framework.decorators import action
|
|
from apps.notification.models import Notification
|
|
from apps.notification.serializers import NotificationSerializer
|
|
|
|
class NotificationViewSet(viewsets.ModelViewSet):
|
|
"""通知视图集"""
|
|
queryset = Notification.objects.all()
|
|
serializer_class = NotificationSerializer
|
|
permission_classes = [IsAuthenticated]
|
|
|
|
def get_queryset(self):
|
|
"""只返回用户自己的通知"""
|
|
return Notification.objects.filter(receiver=self.request.user)
|
|
|
|
@action(detail=True, methods=['post'])
|
|
def mark_as_read(self, request, pk=None):
|
|
"""标记通知为已读"""
|
|
notification = self.get_object()
|
|
notification.is_read = True
|
|
notification.save()
|
|
return Response({'status': 'marked as read'})
|
|
|
|
@action(detail=False, methods=['post'])
|
|
def mark_all_as_read(self, request):
|
|
"""标记所有通知为已读"""
|
|
self.get_queryset().update(is_read=True)
|
|
return Response({'status': 'all marked as read'})
|
|
|
|
@action(detail=False, methods=['get'])
|
|
def unread_count(self, request):
|
|
"""获取未读通知数量"""
|
|
count = self.get_queryset().filter(is_read=False).count()
|
|
return Response({'unread_count': count})
|
|
|
|
@action(detail=False, methods=['get'])
|
|
def latest(self, request):
|
|
"""获取最新通知"""
|
|
notifications = self.get_queryset().filter(
|
|
is_read=False
|
|
).order_by('-created_at')[:5]
|
|
serializer = self.get_serializer(notifications, many=True)
|
|
return Response(serializer.data)
|
|
|
|
def perform_create(self, serializer):
|
|
"""创建通知时自动设置发送者"""
|
|
serializer.save(sender=self.request.user)
|
|
|