Reputation: 759
I got a simple models like this:
class CurrentMonthRegisterPage(models.Manager):
"""This manager class filter with current month."""
current_date = datetime.now().date()
def get_queryset(self):
return super(CurrentMonthRegisterPage, self).get_queryset().filter(
detail_hour__month=self.current_date.month, detail_hour__year=self.current_date.year)
class RegisterPage(models.Model):
OTHERS = '4'
EXTRA_TIME = '3'
EARLIER = '2'
ON_TIME = '1'
LATE = '0'
ABSENT = '-'
STATUS_LIST = (
(LATE, _("Late")),
(ON_TIME, _("On time")),
(EARLIER, _("Earlier")),
(EXTRA_TIME, _("Extra time")),
(OTHERS, _("ND")),
(ABSENT, _("Absent")),
)
detail_hour = models.DateTimeField(_('Date and hour'), auto_now_add=True)
details_mouvement = models.TextField(_("Déscription"), blank=True)
state = models.CharField(_("Statut"), max_length=1, choices=STATUS_LIST, default=ABSENT)
objects = RecentManager()
c_month = CurrentMonthRegisterPage()
Now i want to get a number of every state of every day of current month
Example:
Current month is March
How to get a number of state==LATE of every day of march ?
I want to get something like this:
queryset = [{'late':[1,1,3,5,....31], 'other_state': [1,2,...], ...}]
Please help ?
Upvotes: 0
Views: 45
Reputation: 5740
You need a query with fields for day and state, then you do a count (implicitly grouping by day and state):
from django.db.models import Count
from django.db.models.functions import Trunc
queryset = (RegisterPage.c_month
.annotate(day=Trunc('detail_hour', 'day'))
.values('day', 'state')
.annotate(count=Count('day'))
.order_by('day', 'state')
)
I've added an ordering clause to remove any existing ordering (that would thwart the desired grouping) and to sort the results.
The results only include days and states that are actually present in the data, if you want to include missing days or states with the count 0
, you may want to do it in Python code.
Upvotes: 2