django - 如何在注释中添加查找到计数
问题描述
我想获取所有状态 = 1 的讲座的计数。目前我只能使用以下代码行来计算所有讲座的数量:
topic = Topic.objects.annotate(lectures_count=Count('lectures')).get(id=topic_id)
这是我的模型
class Lecture(models.Model):
id = HashidAutoField(primary_key=True)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='lectures')
status = models.BooleanField(default=1)
class Topic(models.Model):
id = HashidAutoField(primary_key=True)
name = models.CharField(max_length=100, null=False)
status = models.BooleanField(default=1)
解决方案
你可以做:
from django.db.models import Count, Case, When, IntegerField,
Topic.objects.annotate(
lecs_with_status_1=Count(
Case(
When(
lectures__status=1,
then=1
),
output_field=IntegerField()
)
).values('id', 'lecs_with_status_1')
结果,您将获得具有 1 个状态的讲座计数的主题。