inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

파이썬으로 장고(Django) 공략하기: 입문

장고 Queryset 질문이요.

161

startrail.hub

작성한 질문수 1

0

저희 회사 개발자분이 그만둬서,, 제가 이 강의를 아직 듣지는 못했지만 질문 남깁니다.

부서의 매출합계 * 100 / 전체 매출합계로 해서 비중(%)를 구하려고 하는데요.

Mariadb(MySQL)기준으로

SUM(`매출테이블`.매출컬럼) * 100 / SUM(SUM(`매출테이블`.매출컬럼)) OVER() as PER

이러한 컬럼인데요.

제 쿼리셋은

queryset = Sale.objects.all().select_related().values(
).annotate(
dept_nm=F('Department__dept_nm'),
dept_cd=F('Department__dept_cd'),
sal_year=ExtractYear('sal_dt'),
sal_month=ExtractMonth('sal_dt'),
sal_famt=F('sal_famt'),
).values(
'sal_year', 'dept_cd', 'dept_nm'
).annotate(
Jan=Coalesce(Sum(Case(When(sal_month=1, then='sal_famt'),)), 0),
Feb=Coalesce(Sum(Case(When(sal_month=2, then='sal_famt'),)), 0),
Mar=Coalesce(Sum(Case(When(sal_month=3, then='sal_famt'),)), 0),
Apl=Coalesce(Sum(Case(When(sal_month=4, then='sal_famt'),)), 0),
May=Coalesce(Sum(Case(When(sal_month=5, then='sal_famt'),)), 0),
Jun=Coalesce(Sum(Case(When(sal_month=6, then='sal_famt'),)), 0),
Jul=Coalesce(Sum(Case(When(sal_month=7, then='sal_famt'),)), 0),
Aug=Coalesce(Sum(Case(When(sal_month=8, then='sal_famt'),)), 0),
Sep=Coalesce(Sum(Case(When(sal_month=9, then='sal_famt'),)), 0),
Oct=Coalesce(Sum(Case(When(sal_month=10, then='sal_famt'),)), 0),
Nov=Coalesce(Sum(Case(When(sal_month=11, then='sal_famt'),)), 0),
Dec=Coalesce(Sum(Case(When(sal_month=12, then='sal_famt'),)), 0),
Tot=Coalesce(Sum('sal_famt'), 0),
).filter(sal_year=year).order_by('dept_cd')

현재 이런 구조입니다.

Queryset 결과는  dept_nm, dept_cd, sal_year, Jan ~ Dec, Tot 으로 나오구요.

비중(합계)를 MariaDB에서는 Sum() Over()를 쳤는데. 장고 Queryset에서는 어떻게 해야 할까요?

python django

답변 1

0

박순영

이 부분은 강의에서 다루는 내용은 아니지만 아래 링크의 내용을 참고하셔서 annotate와 values, Sum 등을 활용하시면 될 거 같습니다.

https://stackoverflow.com/questions/37851053/django-query-group-by-month

빨간 줄이 뜨네요

0

137

1

import 문장에 빨간줄이 뜹니다.

0

156

1

putty 관련 질문

0

192

1

uWSGI 세팅하기_ 최종 502 bad gateway error

0

809

1

putty 접속관련

0

305

1

[리뷰 삭제하기] 삭제시 path 에러문구나옴.

0

386

1

데이터 새성시 forms.py, models.py 관련문의

0

308

1

'폼으로 데이터 전송하기' 강의 소리가 갑자기 작아짐

0

318

1

[스태틱]index.html 의 이미지를 변경하려면 ?

0

508

1

WARNINGS: ?: (staticfiles.W004) The directory 'C:\projects\first-django\static' in the STATICFILES_DIRS setting does not exist.

0

427

1

사진 넣고 엑박...ㅜㅜ

0

335

0

간단한 웹 페이지 띄우기 강의 10분 후반쯤

0

419

0

리뷰 등록 구현하기 4:26 url 오류

0

347

1

create.html

0

361

1

502 badgateway 오류가 떠요

0

284

0

putty에서 막혔네요 ㅠㅠ

0

355

2

django) 한 폼에 여러 모델 데이터 입력하는 경우

0

328

0

파이참 안에서 가상환경 접속이 안 됩니다.

0

691

1

settings.py

0

305

1

만약 웹앱을 업데이트할경우는 어떻게 해야하나요?

0

374

1

CSS 가운데 정렬 적용 안됨

0

4833

3

NameError: name 'os' is not defined

2

1107

1

1분 26초에 post=Post.objects.create(title="this is title", content="this is content")부분이 실행이 안됩니다.

0

267

1

virtualenv가 설치가 안됩니다..

0

439

1