0

I want to aggregate amount of item for each day separately.

Model:

class Bill(models.Model):
    date = models.DateTimeField()
    amount = models.IntegerField(null=False, blank=False)

Template:

   {% with var=bill.date|date:"Y-m-d" %}
      {{ var }}   #dict?
   {% endwith %}

I think, that add date to dictionary as a key, and count amount of item as a value is a good idea, so I write it:

Dict[var] += bill.amount

How can I use it in Django template?

Am I on the right way? Maybe other solution are better?

Jareq
  • 31
  • 1
  • 7
  • hey, I've seen your comment that you have deleted. I added examples just now. You could have found them by googling/searching on stackoverflow. – Lucas03 Sep 24 '15 at 13:14

1 Answers1

0

Use aggregation/annotate to get sum of amount by date. In template just simply print its value as usually with querysets.

1. If you have datetime with same values (hours, minutes and seconds), you should be able to use the following.

bills = Bill.objects.values('date').annotate(Sum('amount'))

In template just use

{% for bill in bills %}
    {{ bill.date }} - {{ bill.sum__amount }}
{% endfor %}

2. If you have datetime with different hours and you want to group by date and print its sum:

bills = Bill.objects.extra(select={'day': 'date( date )'})\
                    .values('day').annotate(Sum('amount'))

And then print it:

{% for bill in bills %}
    {{ bill.day }} - {{ bill.sum__amount }}
{% endfor %}

3. If you want to do calculations in template, which I strongly do not recommend, have a look at regroup

Community
  • 1
  • 1
Lucas03
  • 2,267
  • 2
  • 32
  • 60