如何从数据库中获取月份名称而不是月份编号



我正在从数据库中挑选一些数据,以便在我的网站中进行一些分析。我正在图表js的帮助下以图形方式呈现数据。

这就是我在视图中的做法,

视图.py

monthly_visitor = VisitorCount.objects.all().filter(date_of_record__year = currentYear.year).values(
'date_of_record__month'
).annotate(
total_in_month=Count('ip') 
).order_by('date_of_record__month')

在这里,我收集了今年每个月所有访客的数据。现在,如果我打印monthly_vistor,我会得到以下结果

<QuerySet [{'date_of_record__month': 9, 'total_in_month': 1}, {'date_of_record__month': 10, 'total_in_month': 2}, {'date_of_record__month': 11, 'total_in_month': 3}, 
{'date_of_record__month': 12, 'total_in_month': 5}]> 

这是正确的,但我想要的是

<QuerySet [{'date_of_record__month': sept, 'total_in_month': 1}, {'date_of_record__month': oct, 'total_in_month': 2}, {'date_of_record__month': nov, 'total_in_month': 3}, 
{'date_of_record__month': dec, 'total_in_month': 5}]> 

这样我就可以在图表中显示月份的名称,而不是数字。我发现了一些在html中使用标记的方法。但是我在ajax的帮助下将这些数据导入到另一个javascript文件中。

请建议我该怎么做。

假设你的代码有效,对于PostgreSQL,你可以这样做:

from django.db.models import F, Func, Value, CharField
monthly_visitor = VisitorCount.objects.all().filter(
date_of_record__year=currentYear.year
).values(
'date_of_record__month'
).annotate(
total_in_month=Count('ip'),
formatted_date=Func(
F('created_at'),
Value('Month'),
function='to_char',
output_field=CharField()
)
).order_by('date_of_record__month')

我使用的是格式化函数,所以这段代码依赖于RDBMS。

QuerySet中还有一个date_of_record__month,您不必将其传递给响应。

最新更新