Skip to main content
 首页 » 编程设计

python之Django 重命名字典值

2025年05月04日27www_RR

我有一本字典

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 月等。我该怎么做?

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

模板.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> 

请您参考如下方法:

在您的 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 %} 
        ],