0

我有一个关于计数对象、过滤结果并最终将它们放入我的模板的问题。

Models.py

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

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

问题是,如何在表格中显示结果,例如:

结果

或者至少让它显示每个月以及该月提到部门的次数。

4

2 回答 2

1

如果您不将关键字传递给annotate,它会使用__count附加到它的字段的名称。https://docs.djangoproject.com/en/dev/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset要在您的模板中访问它,您只需执行以下操作:

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

要水平显示它...

<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>
于 2013-04-10T17:36:15.517 回答
1

你需要类似的东西:

{% for each_model in raport %}
    {{each_model.department}}
    {{each_model.date}}
{% endfor %}
于 2013-04-10T16:35:01.980 回答