【问题标题】:Django Rename dictionary valueDjango重命名字典值
【发布时间】:2017-09-07 14:45:22
【问题描述】:

我有一本字典

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>

【问题讨论】:

  • 好的,你的问题是什么?
  • 如何将 dict 值 1、2、3 更改为一月、二月、三月等..?
  • 你能详细说明一下吗?

标签: python django dictionary


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你可以尝试使用templatefilter-date:

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

    【讨论】:

      【解决方案3】:
      Income.objects.filter(assigned_to__username=self.request.user).\
          extra(select={'month': "MONTHNAME(created)"}).\
          values('month')
      

      【讨论】:

      • 想要解释一下吗?
      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多