Search code examples
djangodjango-querysetdjango-orm

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.


Solution

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