django 2:按当月的每一天筛选模型

时间:2019-03-24 22:39:37

标签: django django-models

我有一个像这样的简单模型:

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()

现在我想获取当月每一天的每种状态的数字

示例:

本月是三月

如何获取三月每天 state == LATE 个数字?

我想得到这样的东西:

queryset = [{'late':[1,1,3,5,....31], 'other_state': [1,2,...], ...}]

请帮助?

1 个答案:

答案 0 :(得分:2)

您需要一个带有日期和状态字段的查询,然后进行计数(隐式按日期和状态分组):

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')
)

我添加了一个ordering子句,以删除任何现有的排序(这将阻碍所需的分组)并对结果进行排序。

结果仅包含数据中实际存在的日期和状态,如果要包含计数为0的缺失日期或状态,则可能需要在Python代码中完成。

相关问题