如何使用django按月查询处理数据

时间:2015-01-08 17:05:07

标签: mysql django django-orm

我确实要求您提供每个月和每年的数据。这意味着我有一些2014年至2015年的数据,我希望将其作为输出{year: 2014, month: 6, count: 15}, {year: 2014, month:8 count: 3}...。其开头随时都可以设置。这是我写的代码:

tournaments = Tournament.objects.extra(select={'month': "MONTH(started)", 'year': "YEAR(started)"},
                                           where=["championship_id = %s AND started >= %s AND ended <= %s"],
                                           params=[championship_id, start_date, end_date])\
        .values("month", "year")\
        .annotate(Count('started'))

在一个月内started和另一个月ended有证据的情况下,这一切都很顺利。然后我只提取一个月的数据。对我来说,你必须把它们拿出来,在两个月内都有它们。怎么会发生这种情况?这可能发生在查询中吗?

model.py

class Tournament (LocalizedModel):
    criteria = models.ForeignKey (EntryCriteria,verbose_name=_('entry criteria'), null=True, blank=True, on_delete=models.SET_NULL)
    championship = models.ForeignKey(Championship, verbose_name=_('part of championship'), on_delete=models.PROTECT)
    round_rank_points = models.ForeignKey(TournamentRoundRankPoints, verbose_name=_('Tournament scoring'), on_delete=models.PROTECT)
    name = LocalizedField(models.CharField(verbose_name=_('name'), max_length=100, unique=True))
    started = models.DateTimeField (_('start date and time'))
    ended = models.DateTimeField (_('end date and time'), null = True, blank=True)
    club = models.ForeignKey(Club, verbose_name=_('at club'), on_delete=models.PROTECT)

0 个答案:

没有答案