Django重命名字典值

时间:2017-09-07 14:45:23

标签: python django dictionary

我有一本字典

context['income'] = Income.objects.filter(assigned_to__username=self.request.user). \
                                   filter(status=Income.STATUS_PENDING). \
                                   annotate(month=ExtractMonth('created')).values('month'). \
                                   annotate(value=Coalesce(Sum('value'), 0)).values('month', 'value')

每次都会返回:

<QuerySet [{'month': 9, 'value': Decimal('12.50')}]>

相反,月份编号我希望以单词显示月份: 1 - 1月,2月 - 2月... 9 - 9月等我该怎么做?

我想在图表中使用它,每月会显示一个月的总价值。

template.html

<script type="text/javascript">
    $(document).ready(function () {
        Morris.Bar({
            element: 'Income',
            data: [
                {% for item in income %}
                    { Month: '{{ item.month }}', Income: '{{ item.value }}' },
                {% endfor %}
            ],
            xkey: 'Month',
            ykeys: ['Income'],
            labels: ['Euro'],
            resize: true,
            lineColors: ['#33414E', '#95B75D']
        });
    });
</script>

3 个答案:

答案 0 :(得分:4)

JS中的简单数组查找是最简单的方法。

$(document).ready(function () {
    monthNames = ['January', 'February', 'March', 'April', ...];
    Morris.Bar({
        element: 'Income',
        data: [
            {% for item in income %}
                { Month: monthNames[{{ item.month }} - 1], Income: '{{ item.value }}' },
            {% endfor %}
        ],

答案 1 :(得分:1)

您可以尝试使用templatefilter-date

{ Month: '{{ item.month|date:"F" }}', Income: '{{ item.value }}' },

答案 2 :(得分:0)

Income.objects.filter(assigned_to__username=self.request.user).\
    extra(select={'month': "MONTHNAME(created)"}).\
    values('month')