Django重命名字典值

2024-03-29 07:42:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典

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')}]>

相反,我希望用文字显示月份: 一月一日,二月二日。。。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>

Tags: to字典objectsvaluecontextscriptfilteritem
3条回答
Income.objects.filter(assigned_to__username=self.request.user).\
    extra(select={'month': "MONTHNAME(created)"}).\
    values('month')

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

您可以尝试使用templatefilter-date

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

相关问题 更多 >