Hello everyone,
I am wandering if there is an easy way to build graphics showing evolution a the number of objects over the time.
Here are my models :
class Category(models.Model):
name = models.CharField(max_length=255)
class Incident(models.Model):
title = models.CharField(max_length=255, null=False)
start_date = models.DateTimeField()
resolving_date = models.DateTimeField()
category = models.ForeignKey(Category)
I made a view to retrieve, for the last 30 days, the number of incidents by category :
class IncidentByCategoryOverTimeView(APIView):
def by_category(self, incidents, categories, single_date):
slot_max = single_date.replace(hour=23, min=59, second=59, microsecond=999999)
by_category={}
by_category['name'] = date.strftime(single_date, "%d-%m-%Y")
for category in categories:
by_category[category.name] = incidents.filter(category__name=category.name).filter(Q(start_date__lt=slot_max, resolving_date__gt=slot_max)).distinct().count()
return by_category
def get(self, request, *args, **kwargs):
frame = 30
incidents = Incident.objects.all()
stats = []
categories = Categories.objects.all()
for single_date in ((timezone.now() - timedelta(frame - 1) + timedelta(n)).replace(tzinfo=timezone.gett_current_timezone(), hour=0, min=0, second=0, microsecond=0) for n in range(frame)):
stats.append(self.by_category(incidents, categories, single_date))
return response.Response(stats, status=status.HTTP_200_OK)
The output will be something like :
[
{
"name": "20-09-2023"
"Critical": 10,
"Medium": 15,
},
{
"name": "21-09-2023"
"Critical": 9,
"Medium": 10,
},
...
]
Do you think there is a better way to do that ?