4

I need to create a report in which I can get the value for each month of the year.

models.py

class Ask(models.Model):
      team = models.CharField(max_length=255)
      date = models.DateField()

In team are only three possible values: A, B, C.

How do I calculate how many times a month was added individual team?

I would like to generate a report for each year.

MalT
  • 313
  • 2
  • 12

1 Answers1

3

I suggest you to add month field to your model and pass there month on save. This is help you to run this:

from django.db.models import Count
Ask.objects.filter(date__year='2013').values('month', 'team').annotate(total=Count('team'))

Other method is to use extra parameter and extract month from date field:

from django.db.models import Count
Ask.objects.filter(date__year='2013').extra(select={'month': "EXTRACT(month FROM date)"}).values('month', 'team').annotate(Count('team'))

but EXTRACT method is database dependent and for example dont`t work in SQLite

Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43
  • +1 for `EXTRACT`. [In SQLite you'd have to use](http://www.sqlite.org/lang_datefunc.html) `STRFTIME(date, "%m")` – Gareth Rees Apr 05 '13 at 08:42
  • Works fine, but only how to add to the template to make it look like this: 2013-01 team A = 2, 2013-02 team A = 1, 2013-03 team A = 7... Now i have {'team__count': 5, 'team': u'A', 'month': 3.0} – MalT Apr 05 '13 at 09:11
  • to access dict values in template read this: http://stackoverflow.com/questions/8000022/django-template-how-to-lookup-a-dictionary-value-with-a-variable – Lukasz Koziara Apr 05 '13 at 09:23
  • or prepare your data in simple list and just iterate over it in template – Lukasz Koziara Apr 05 '13 at 09:26