【问题标题】:Django ORM to retrieve month name from date timeDjango ORM 从日期时间检索月份名称
【发布时间】:2018-12-22 10:50:15
【问题描述】:

我需要用相应月份的总价检索月份名称。 这是我的订单表示例

我的尝试是:

month_wise_sales = Order.objects\
.annotate(month=ExtractMonth('created_at'))\
.values('month')\
.annotate(total_sales=Sum('total_price'))

它会返回

<QuerySet [{'month': 7, 'total_sales': Decimal('138400.00')}, {'month': 9, 'total_sales': Decimal('1150.00')}]>

我的愿望是这样的

[{'month': July, 'total_sales': Decimal('138400.00')}, {'month': September, 'total_sales': Decimal('1150.00')}]

如何解决?

【问题讨论】:

标签: sql django django-queryset django-orm


【解决方案1】:

这对我来说很好。 工作查询

month_wise_sales = Order.objects\
.annotate(month=Cast('created_at', DateField()))\
.values('month')\
.annotate(total_sales=Sum('total_price'))

然后在模板中使用这个

{{ monthly_sales.month | date:"M"}}

这样,我将得到带有月份名称的总价格的总和。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-11
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多