Skip to content

Commit

Permalink
feat(stats): add queryset to Stat model
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Oct 2, 2023
1 parent 9c799d6 commit 2bbfa18
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lacommunaute/forum_stats/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -19,3 +29,5 @@ class Meta:

def __str__(self):
return f"{self.name} - {self.date} - {self.period}"

objects = StatQuerySet().as_manager()
17 changes: 17 additions & 0 deletions lacommunaute/forum_stats/tests.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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)

0 comments on commit 2bbfa18

Please sign in to comment.