python – Grouping by Months Years Weeks

Question:

Here is the model I need to group the Report model by week months or by year I tried this

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

I can of course use filter but I need it with values help me what I'm doing wrong

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


class Profile(models.Model):
        first_name = models.CharField(max_length=100, verbose_name=_('Имя'))
        last_name = models.CharField(max_length=100, verbose_name=_('Фамилия'))
        user = models.OneToOneField(User, related_name='profile', verbose_name=_('Профиль'))
        phone = models.BigIntegerField(null=True, blank=True, verbose_name=_('Номер телефона'))
        photo = models.ImageField(upload_to='profile_image', verbose_name=_('Фото'), null=True, blank=True)
        sex = models.CharField(max_length=30, choices=GENDER, verbose_name=_('Выбор пола'))
        date_of_birth = models.DateField(null=True, blank=True)
        department = models.ForeignKey('reports.Department', related_name='department')
        position = models.CharField(max_length=120)

        class Meta:
            verbose_name = _('Профиль')
            verbose_name_plural = _('Профили')

Answer:

Thanks guys, I figured it out myself and that's how I did it

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

here he sorts by month

Scroll to Top