python - Django 重命名字典值

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

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

模板.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 %}
        ],

关于python - Django 重命名字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46099295/

相关文章:

python - 使用 django-social-auth (omab) 自动刷新访问 token

python - Python中字典和pandas系列的区别

python - 如何在绘图中添加粗体注释文本

python - 在 python 中更新/附加到 json(嵌套)

python - 向 Django 模型添加动态字段

python - 如何在django admin中显示与某个用户相关的记录

python - cx_Freeze 无法找到 mkl : MKL FATAL ERROR: Cannot load mkl_intel_thread. dll

python - 从 python 文件中读取单个字符?

c++ - 在循环中使用新指针填充 map (C++)

scala - Scala 中 Map.clear 的时间复杂度