Skip to content

Notifications API Reference

notifications.models

Models for the notifications application.

Defines the structure for systemic and event-driven notifications sent to users (e.g., budget alerts, goal achievements).

Notification

Bases: Model

Represents a single message or alert sent to a user.

Attributes:

Name Type Description
user ForeignKey

The recipient of the notification.

type CharField

Classification (Budget Alert, System, etc.).

title CharField

Short descriptive heading.

message TextField

The full body content.

is_read BooleanField

Tracks if the user has seen the alert.

created_at DateTimeField

When the alert was generated.

Source code in notifications/models.py
class Notification(models.Model):
    """
    Represents a single message or alert sent to a user.

    Attributes:
        user (ForeignKey): The recipient of the notification.
        type (CharField): Classification (Budget Alert, System, etc.).
        title (CharField): Short descriptive heading.
        message (TextField): The full body content.
        is_read (BooleanField): Tracks if the user has seen the alert.
        created_at (DateTimeField): When the alert was generated.
    """

    TYPE_BUDGET_ALERT = 'budget_alert'
    TYPE_SAVINGS_REMINDER = 'savings_reminder'
    TYPE_TRANSACTION_ALERT = 'transaction_alert'
    TYPE_GOAL_ACHIEVEMENT = 'goal_achievement'
    TYPE_SYSTEM = 'system'

    TYPE_CHOICES = [
        (TYPE_BUDGET_ALERT, 'Budget Alert'),
        (TYPE_SAVINGS_REMINDER, 'Savings Reminder'),
        (TYPE_TRANSACTION_ALERT, 'Transaction Alert'),
        (TYPE_GOAL_ACHIEVEMENT, 'Goal Achievement'),
        (TYPE_SYSTEM, 'System'),
    ]

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='notifications')
    type = models.CharField(max_length=20, choices=TYPE_CHOICES)
    title = models.CharField(max_length=200)
    message = models.TextField()
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        """Metadata for the Notification model."""
        ordering = ['-created_at']

    def __str__(self):
        """Return a string summary of the notification."""
        return f'{self.type} - {self.title}'

Meta

Metadata for the Notification model.

Source code in notifications/models.py
class Meta:
    """Metadata for the Notification model."""
    ordering = ['-created_at']

__str__()

Return a string summary of the notification.

Source code in notifications/models.py
def __str__(self):
    """Return a string summary of the notification."""
    return f'{self.type} - {self.title}'

notifications.serializers

Serializers for the notifications application.

Handles the conversion of notification instances into JSON data.

NotificationSerializer

Bases: ModelSerializer

Serializer for the Notification model.

Exposes core fields including read status and creation timestamp.

Source code in notifications/serializers.py
class NotificationSerializer(serializers.ModelSerializer):
    """
    Serializer for the Notification model.

    Exposes core fields including read status and creation timestamp.
    """

    class Meta:
        """Metadata for NotificationSerializer."""
        model = Notification
        fields = ['id', 'type', 'title', 'message', 'is_read', 'created_at']
        read_only_fields = ['id', 'created_at']

Meta

Metadata for NotificationSerializer.

Source code in notifications/serializers.py
class Meta:
    """Metadata for NotificationSerializer."""
    model = Notification
    fields = ['id', 'type', 'title', 'message', 'is_read', 'created_at']
    read_only_fields = ['id', 'created_at']

notifications.views

Views for handling user notifications and read status.

Provides endpoints to list notifications, mark them as read individually, or mark all as read simultaneously.

NotificationViewSet

Bases: ModelViewSet

ViewSet for managing user notifications.

Supports listing, creation (systemic), and state changes (marking as read).

Source code in notifications/views.py
class NotificationViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing user notifications.

    Supports listing, creation (systemic), and state changes (marking as read).
    """

    serializer_class = NotificationSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        """
        Return notifications filtered by the currently authenticated user.

        Returns:
            QuerySet: Authenticated user's notifications.
        """
        return Notification.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        """
        Automatically link the authenticated user to newly created notifications.

        Args:
            serializer (NotificationSerializer): The validated notification serializer.
        """
        serializer.save(user=self.request.user)

    @extend_schema(
        summary="Mark All Notifications as Read",
        description="Updates all notifications for the authenticated user to 'is_read=True'.",
        request=None, 
        responses={200: None}
    )
    @action(detail=False, methods=['post'])
    def mark_all_read(self, request):
        """
        Mark every notification for the user as read.

        Returns:
            Response: Success confirmation message.
        """
        self.get_queryset().update(is_read=True)
        return Response({'message': 'All notifications marked as read'})

    @extend_schema(
        summary="Mark Notification as Read",
        description="Sets 'is_read=True' for a specific notification identified by ID.",
        request=None, 
        responses={200: None}
    )
    @action(detail=True, methods=['post'])
    def mark_read(self, request, pk=None):
        """
        Mark a single notification as read by its primary key.

        Args:
            pk (int): Primary key of the notification.

        Returns:
            Response: Success confirmation message.
        """
        notification = self.get_object()
        notification.is_read = True
        notification.save()
        return Response({'message': 'Notification marked as read'})

get_queryset()

Return notifications filtered by the currently authenticated user.

Returns:

Name Type Description
QuerySet

Authenticated user's notifications.

Source code in notifications/views.py
def get_queryset(self):
    """
    Return notifications filtered by the currently authenticated user.

    Returns:
        QuerySet: Authenticated user's notifications.
    """
    return Notification.objects.filter(user=self.request.user)

mark_all_read(request)

Mark every notification for the user as read.

Returns:

Name Type Description
Response

Success confirmation message.

Source code in notifications/views.py
@extend_schema(
    summary="Mark All Notifications as Read",
    description="Updates all notifications for the authenticated user to 'is_read=True'.",
    request=None, 
    responses={200: None}
)
@action(detail=False, methods=['post'])
def mark_all_read(self, request):
    """
    Mark every notification for the user as read.

    Returns:
        Response: Success confirmation message.
    """
    self.get_queryset().update(is_read=True)
    return Response({'message': 'All notifications marked as read'})

mark_read(request, pk=None)

Mark a single notification as read by its primary key.

Parameters:

Name Type Description Default
pk int

Primary key of the notification.

None

Returns:

Name Type Description
Response

Success confirmation message.

Source code in notifications/views.py
@extend_schema(
    summary="Mark Notification as Read",
    description="Sets 'is_read=True' for a specific notification identified by ID.",
    request=None, 
    responses={200: None}
)
@action(detail=True, methods=['post'])
def mark_read(self, request, pk=None):
    """
    Mark a single notification as read by its primary key.

    Args:
        pk (int): Primary key of the notification.

    Returns:
        Response: Success confirmation message.
    """
    notification = self.get_object()
    notification.is_read = True
    notification.save()
    return Response({'message': 'Notification marked as read'})

perform_create(serializer)

Automatically link the authenticated user to newly created notifications.

Parameters:

Name Type Description Default
serializer NotificationSerializer

The validated notification serializer.

required
Source code in notifications/views.py
def perform_create(self, serializer):
    """
    Automatically link the authenticated user to newly created notifications.

    Args:
        serializer (NotificationSerializer): The validated notification serializer.
    """
    serializer.save(user=self.request.user)