Jaehan Park
Jaehan Park

Reputation: 103

Django queryset TruncMonth output format issue

I'm using Django ORM queryset for chart, and having difficulty with changing the format of output

'source': ActivityLog.objects.filter(requestType='add',doDate__lte=datetime.datetime.today(), doDate__gt=datetime.datetime.today()-datetime.timedelta(days=365)).\
                   values(작업월=TruncMonth('doDate')).annotate(요청건수=Count('requestType'), IP개수=Sum('ipCnt'))},

When I use 'TruncMonth' , output is like this -> 2019-10-01T00:00:00

But I want to use only 2019-10 ( YYYY-MM )...

Is there any good solution for me?

Thanks in advance.

Upvotes: 4

Views: 784

Answers (2)

Akshay Vijay Jain
Akshay Vijay Jain

Reputation: 15935

The purpose over here of TruncMonth is to make 1st January and 10th January equal, so that, these values can be group by Month.
If you want to print the month, you can simply print using doDate as

print(doDate.year,'-',doDate.month)

Upvotes: 0

funnydman
funnydman

Reputation: 11326

If you want to use it as a string after that, you could do:

from django.db.models import DateField, CharField
from django.db.models.functions import TruncMonth, Cast, Substr

ActivityLog.objects.values(
        result=Substr(
            Cast(TruncMonth('doDate', output_field=DateField()),
                 output_field=CharField()), 1, 7)
    )

Upvotes: 6

Related Questions