python

Django orm - group by해서 count 얻는 경우

wangkisa 2019. 7. 10. 16:27

특정 모델에서 예를 들어 특정 조건의 누적된 사람 수를 구해야 하는 경우

 

user_id 가 지정된 유저의 id 라고 할때 

다음과 같이 호출하면

 

변수명 = 모델명.objects.values('user_id').filter(
            조건~~~
        ).annotate(Count('user_id')).aggregate(count=Count('user_id'))

 

 

변수명에 'count' = 123123 이런식으로 나오는 것을 알 수 있다.

 

 

변수명 = 모델명.objects.values('user_id').filter(
            조건~~~
        ).annotate(Count('user_id'))

처럼 해서 무언가 될줄 알고 삽질을 여러번 했지만 안되서 뒤에  aggregate 와 같이 써야만 정확히

특정 조건의 누적된 사람 수를 알수 있었다.