'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 1:[1]
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)
)
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Akshay Vijay Jain |