Home > Blockchain >  How to get the name of the month instead of the month number from db
How to get the name of the month instead of the month number from db

Time:12-26

I am picking some data from the db to make some analytics in my website. I am rendering out the data graphically with the help of chart js.

This is how I am doing it in views,

views.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')
    

Here, I am picking up the data of all the visitors of every month of the current year. Now if I print the monthly_visitor I get the below result

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

Which is correct but what I want is

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

So that I can display names of the month in the graph rather the numbers. I came across some methods to use tags in the html. But I am importing this data into a different javascript file with the help of ajax.

Please suggest me what should I do.

CodePudding user response:

Assuming your code works, for PostgreSQL you can do it this way:

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

I'm using the formatting functions, so this code is RDBMS-dependent.

You will also have a date_of_record__month in QuerySet, you don't have to pass it to the response.

  • Related