반응형
간단한 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
반응형
'파이썬' 카테고리의 다른 글
파이썬 Python으로 소리 재생 (0) | 2020.11.23 |
---|---|
파이썬 Python Nose Import Error (0) | 2020.11.23 |
파이썬 Python을 사용하여 HTML에서 href 링크를 얻으려면 어떻게해야합니까? (0) | 2020.11.22 |
파이썬 Apache Spark 사전 빌드 버전에서 spark-csv와 같은 새 라이브러리를 추가하는 방법 (0) | 2020.11.22 |
파이썬 팬더의 가져 오기 오류를 해결하는 방법은 무엇입니까? (0) | 2020.11.22 |
댓글