장고

2017-12-19 2 views
0

가 나는'ModelParent은 '여기, 많은'ModelChild '을 가지고 내 모델 구조입니다 두 가지 모델'ModelParent '와'ModelChild을 '이 작동하지 않는 필터 주석을 카운트 ModelChild '데이터베이스에 현재 유일한'ModelParent '에 속하는'ModelChild '의'type '값이'1 '과 같으면'ModelParent '개체가 생겨 집계해야합니다. 타입이 '1'인 'childs'의 수와 타입이 '2'인 'childs'의 수를 계산하면 다음과 같습니다.장고

queryset = ModelParent.objects \ 
     .annotate(first_count=Count('childs', filter=Q(childs__type=1))) \ 
     .annotate(second_count=Count('childs', filter=Q(childs__type=2))).get(pk=1) 

쿼리에서 오류가 발생하지 않지만 응답을 볼 때 두 주석의 값은 'first_count'의 경우 '1'이고 'second_count'의 경우 '0'이어야하는 경우 '1'입니다.

필터 "filter = Q (childs__type = 1)"내에서 'childs__type'으로 설정 한 값이 아무리 중요하더라도 결과는 항상 동일하므로 다음과 같이 설정할 수 있습니다. ' childs__type = 10 '이고 여전히 카운트가'1 '과 같습니다. 전체'필터 '매개 변수가 무시되는 것과 같습니다.

답변

0

this answer에 기반을 두어이 방법으로 달성했지만 필자는 'output_field'를 하위 쿼리에 추가하고 'Coalesce'를 주석에 추가해야했습니다. 'output_field'는 django에서 필요했습니다. 'Coalesce'는 결과가 0 인 경우 기본적으로 하위 쿼리가 'null'을 반환하므로 결과가 null 일 때마다 기본값을 검색하는 것이므로 'Coalesce'가 필요합니다. 이 경우 0으로 설정하십시오.

childs_base_query = ModelChild.objects.filter(parent=OuterRef('pk')) 
    first_type_query = Subquery(childs_base_query 
          .filter(type=1) 
          .values('parent') 
          .annotate(count=Count('pk')) 
          .values('count') 
          , output_field=IntegerField()) 

    second_type_query = Subquery(childs_base_query 
           .filter(type=2) 
           .values('parent') 
           .annotate(count=Count('pk')) 
           .values('count') 
           , output_field=IntegerField()) 

    queryset = ModelParent.objects \ 
     .annotate(first_count=Coalesce(first_type_query, 0)) \ 
     .annotate(second_count=Coalesce(second_type_query, 0)) 

다른 사람들에게 도움이되기를 바랍니다.