[Django] annotate DateTimeField 지난 달 구하기
2024. 1. 5. 09:20ㆍPython/Django
목차
설명
Django ORM에서 annotate를 사용해 기존 필드의 지난 달을 구하는 방법입니다.
전체 ORM
Model.objects.annotate(
last_month=ExpressionWrapper(
TruncMonth(
F('created_date'),
output_field=DateTimeField()
)-timedelta(days=1),
output_field=DateTimeField()
),
).annotate(
last_month_yymm=Func(
F('last_month'),
Value('YYMM'),
function='to_char',
output_field=CharField()
)
)
부분 설명
1. 해당 월의 1일 구하기
ex) 2023-12-12 -> 2023-12-01
TruncMonth(
F('created_date'),
output_field=DateTimeField()
)
2. 전달의 말일 구하기
ex) 2023-12-01 -> 2023-11-30
ExpressionWrapper(
TruncMonth(
F('created_date'),
output_field=DateTimeField()
)-timedelta(days=1),
output_field=DateTimeField()
),
ExpressionWrapper를 통해서 DateTimeField로 바꿔줌으로써
Expression contains mixed types: DateTimeField, DurationField. You must set output_field
해당 에러를 방지할 수 있습니다.
3. '%y%m' 형식으로 변경
ex) 2023-12-01 -> 2312
last_month_yymm=Func(
F('last_month'),
Value('YYMM'),
function='to_char',
output_field=CharField()
)
'Python > Django' 카테고리의 다른 글
[Django] CPU 사용량 증가 원인 파악(FilterSet model) (0) | 2024.02.16 |
---|---|
[Django] 스로틀링(Throttling) - 요청 속도 제어 (0) | 2024.01.12 |
[Django] Cache(캐시) (1) | 2024.01.03 |
[Django] Django model on_delete 종류 (0) | 2023.12.20 |
simple history 이력 확인 (0) | 2023.10.16 |