It looks like a simple question, but I am not being able to get the expected results. I have a table like this:
| id# | Concept | Amount | Date |
| ... | ... | 10 | 10/12/2013 |
| ... | ... | 20 | 12/12/2013 |
| ... | ... | 30 | 02/01/2014 |
| ... | ... | 40 | 03/01/2014 |
| ... | ... | 50 | 04/02/2014 |
| ... | ... | 60 | 05/02/2014 |
I would like to find a way to get a QuerySet with this table:
| Date.year | Amount |
| 2013 | 30 |
| 2014 | 180 |
and I guess I would be able to get in a similar way, something like:
| Date.month | Amount |
| 12/2013 | 30 |
| 01/2014 | 70 |
| 02/2014 | 110 |
Any ideas?
EDIT
I will try to clarify, sorry for any misunderstanding or bad explanation :-/
I have this model:
from django.db import models
from django.core.urlresolvers import reverse
class Expense(models.Model):
concept = models.CharField(max_length=255)
date = models.DateField()
amount = models.DecimalField(max_digits=7,decimal_places=2)
class Meta:
ordering = ['date']
def __unicode__(self):
return '%s' % (self.concept)
def get_absolute_url(self):
I have this template:
...
<table>
{% for year in years %}
<tr>
<td width="40%">
{{ year.year }}
</td>
<td width="60%" align="right">{{ year.total_amount }}</td>
</tr>
{% endfor %}
</table>
...
I am trying to find a QuerySet for my view
:
def index(request):
years = Expense.objects.values('date').annotate(total_amount=Sum('amount'))
return render(request, 'account/index.html', {'years': years})
In this case, years
is returning something "close" to what I want, because it is grouping the expenses
by date, but I would like to group them by month or year, instead of "day".
I do not know what is the best way to do this, with a query to Expense or in the template, or some other way. That is what I need. I hope that now is a bit clearer.