Verified Commit 0bd32ef1 authored by David Haynes's avatar David Haynes 🙆

Return active Alerts by default

- ?all_alerts to request all alerts
- is_active function checks if the current Alert is active
parent e2ed1e43
Pipeline #1446 passed with stage
in 1 minute and 35 seconds
......@@ -18,6 +18,7 @@ from django.db import models
from django.contrib.gis.db.models import PointField
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from django.utils import timezone
# Other Imports
from model_utils.models import TimeStampedModel
......@@ -359,6 +360,14 @@ class Alert(TimeStampedModel):
# The date + time that the alert will stop being served
end_datetime = models.DateTimeField()
def is_active(self):
"""
Check if the current Alert object is active (Alert-able).
"""
# Get the current datetime
now = timezone.now()
return self.start_datetime < now < self.end_datetime
def __str__(self):
"""
String representation of an Alert object.
......
......@@ -42,7 +42,7 @@ class AlertViewSet(viewsets.ReadOnlyModelViewSet):
[GET /api/alerts/](/api/alerts/?format=json)
Return all Alert objects.
Return all active Alert objects.
## Built-in query parameters
......@@ -83,6 +83,14 @@ class AlertViewSet(viewsets.ReadOnlyModelViewSet):
[GET /api/alerts/?urgency_tag=major](/api/alerts/?urgency_tag=major&format=json)
Return all Alert objects that are tagged as "major" urgency.
## Custom query parameters
### **all_alerts**
[GET /api/alerts/?all_alerts](/api/alerts/?all_alerts&format=json)
Return all Alert objects.
"""
# All model fields that are available for filtering
FILTER_FIELDS = (
......@@ -108,7 +116,21 @@ class AlertViewSet(viewsets.ReadOnlyModelViewSet):
Handle incoming GET requests and enumerate objects that get returned by
the API.
"""
return Alert.objects.all()
# Define ?all_alerts
all_alerts = self.request.query_params.get('all_alerts', None)
# Return all Alert objects if requested
if all_alerts is not None:
return Alert.objects.all()
# Default behavior
else:
alertable = []
# Enumerate all Alert objects that are active
for alert in Alert.objects.all():
if alert.is_active():
alertable.append(alert.pk)
# Return active Alerts
return Alert.objects.filter(pk__in=alertable)
class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
"""
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment