我想按月分组怎么办?在django

时间:2016-09-24 12:58:52

标签: linux django

sumary = Profile.objects.values(' user_report__created_date__month')

错误 无法解析关键字' month'进入田野。加入' created_date'不允许。

    class Profile(models.Model):
        first_name = models.CharField(max_length=100, verbose_name=_('Имя'))
        last_name = models.CharField(max_length=100)



class Department(models.Model):
    number = models.IntegerField(default=0)
    name = models.CharField(max_length=150, default=None)

    def __unicode__(self):
        return self.name


class Report(models.Model):
    user = models.ForeignKey(Profile, related_name='user_report')
    department = models.ForeignKey(Department, related_name='report')
    created_date = models.DateTimeField()
    edited_by = models.ForeignKey(User)
    edited_at = models.DateTimeField(default=timezone.now())

    def __unicode__(self):
        return self.department.name

    class Meta:
        verbose_name = _('Отчет')
        verbose_name_plural = _('Отчеты')


class Statistic(models.Model):
    name = models.CharField(max_length=90)
    value = models.IntegerField()
    report = models.ForeignKey(Report, related_name='stat_report')

    def __unicode__(self):
        return self.name

2 个答案:

答案 0 :(得分:0)

你可能想要这样的东西:

end_date = datetime.datetime.now() - datetime.timedelta(days=31)
start_date = datetime.datetime.now()
summary = Profile.objects.filter(user_report__range=(start_date, end_date))

这是为了让用户报告一个月。那是对的吗?如果您想要更准确的答案,请添加更多代码。

答案 1 :(得分:0)

我做到了

 truncate_date = connection.ops.date_trunc_sql('month', 'created_date')
    qs = Profile.objects.extra({'date': truncate_date})
    report = qs.values('user_report__stat_report__name', 'date').filter(
        id=profiles_id).annotate(Sum('user_report__stat_report__value'))

感谢的