0

I have a question regarding counting objects, filtering the results and finally putting them into my template.

in Models.py:

class Fms(models.Model):
    department = models.CharField(max_length=255, verbose_name='Department')
    date = models.DateField()

in Views.py:

def raport(request):
    raport = Fms.objects.filter(date__year='2013').extra(select={'month': "EXTRACT(month FROM date)"}).values('month', 'department').annotate(Count('department'))
    return render_to_response ('Fms/raport.html',
                               {'raport': raport},
                               context_instance=RequestContext(request))

Question is, how to show a result in a table like:

Result

Or at least make it show each month and how many times department was mentioned in that month.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
InKline
  • 23
  • 5
  • are you asking about what sql statement should you use, or how to display the information from request context in your template? – psychok7 Apr 10 '13 at 14:59
  • I would like to display the information from request in my template. Thank you for answer. – InKline Apr 10 '13 at 16:28

2 Answers2

1

you need something like:

{% for each_model in raport %}
    {{each_model.department}}
    {{each_model.date}}
{% endfor %}
psychok7
  • 5,373
  • 9
  • 63
  • 101
1

If you do not pass a keyword to annotate, it uses the name of the field with __count appended to it. https://docs.djangoproject.com/en/dev/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset To access that in your template you would simply do:

<table>
    <thead>
        <tr>
            <th>Month</th>
            <th>Count</th>
        </tr>
    </thead>
    <tbody>
        {% for item in raport %}
            <tr>
                <td>{{ item.month }}</td>
                <td>{{ item.department__count }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

To display it horizontally...

<table>
    <thead>
        <tr>
            {% for item in raport %}
                <th>{{ item.month }}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        <tr>
            {% for item in raport %}
                <td>{{ item.department__count }}</td>
            {% endfor %}
        </tr>
    </tbody>
</table>
Ngenator
  • 10,909
  • 4
  • 41
  • 46
  • After using your solution, the result looks like this: http://i47.tinypic.com/bjd3qf.jpg How can i get months horizontally and then show number of department occurences in those months like in image attached in my first post? Regards – InKline Apr 11 '13 at 10:52