diff --git a/lacommunaute/forum_stats/models.py b/lacommunaute/forum_stats/models.py index 496ac70c7..dd01c2cba 100644 --- a/lacommunaute/forum_stats/models.py +++ b/lacommunaute/forum_stats/models.py @@ -3,6 +3,16 @@ from lacommunaute.forum_stats.enums import Period +class StatQuerySet(models.QuerySet): + def current_month_datas(self): + qs = Stat.objects.filter(period="month").order_by("-date") + + if qs.exists(): + return Stat.objects.filter(date=qs.first().date, period=Period.MONTH).values("name", "value", "date") + + return Stat.objects.none() + + class Stat(models.Model): name = models.CharField(max_length=30, verbose_name="Nom") date = models.DateField(verbose_name="Date") @@ -19,3 +29,5 @@ class Meta: def __str__(self): return f"{self.name} - {self.date} - {self.period}" + + objects = StatQuerySet().as_manager() diff --git a/lacommunaute/forum_stats/tests.py b/lacommunaute/forum_stats/tests.py index 9b3307fa7..3e4efc1d0 100644 --- a/lacommunaute/forum_stats/tests.py +++ b/lacommunaute/forum_stats/tests.py @@ -1,9 +1,12 @@ +from dateutil.relativedelta import relativedelta from django.db import IntegrityError from django.test import TestCase from django.utils import timezone +from django.utils.timezone import localdate from lacommunaute.forum_stats.enums import Period from lacommunaute.forum_stats.factories import StatFactory +from lacommunaute.forum_stats.models import Stat class StatModelTest(TestCase): @@ -14,3 +17,17 @@ def test_uniqueness(self): StatFactory(name=name, date=date, period=period) with self.assertRaises(IntegrityError): StatFactory(name=name, date=date, period=period) + + +class StatQuerySetTest(TestCase): + def test_ordering(self): + today = localdate() + stat = StatFactory(period=Period.MONTH, date=today) + StatFactory(period=Period.DAY, date=today) + StatFactory(period=Period.MONTH, date=today - relativedelta(months=1)) + + qs = Stat.objects.current_month_datas() + self.assertEqual(list(qs), [{"name": stat.name, "value": stat.value, "date": today}]) + + def test_empty_dataset(self): + self.assertEqual(Stat.objects.current_month_datas().count(), 0)