본문 바로가기
파이썬

파이썬 How to filter objects for count annotation in Django?

by º기록 2020. 11. 22.
반응형

간단한 Django 모델 Event Participant 를 고려하십시오.

class Event(models.Model):
    title = models.CharField(max_length=100)

class Participant(models.Model):
    event = models.ForeignKey(Event, db_index=True)
    is_paid = models.BooleanField(default=False, db_index=True)

총 참가자 수로 이벤트 쿼리에 쉽게 주석을 달 수 있습니다.

events = Event.objects.all().annotate(participants=models.Count('participant'))

is_paid = True 로 필터링 된 참가자 수를 주석으로 추가하는 방법은 무엇입니까?

참가자 수에 관계없이 모든 이벤트 를 쿼리해야합니다 (예 : 주석이 달린 결과로 필터링 할 필요가 없습니다. 참가자가 0 명이면 괜찮습니다. 주석이 달린 값에 0 만 있으면됩니다.



events = Event.objects.all().annotate(paid_participants=models.Sum(
    models.Case(
        models.When(participant__is_paid=True, then=1),
        default=0,
        output_field=models.IntegerField()
    )))


 

해결 방법

 


어쨌든, 귀하의 경우에는 다음과 같이 간단한 것을보고 있습니다.

from django.db.models import Q, Count
events = Event.objects.annotate(
    paid_participants=Count('participants', filter=Q(participants__is_paid=True))
)


 

참조 페이지 https://stackoverflow.com/questions/30752268

 

 

반응형

댓글