我向数据库编写了3个查询以获取不同的值。我需要将这些查询合并为一个查询。
# Counting Total Number of Plans by Day
Day.objects.annotate(num_of_plans=Count('plan')) \
.values('num_of_plans', 'date', 'id')
# Counting is_completed=True Plans by Day
Day.objects \
.filter(plan__is_completed=True) \
.annotate(num_of_completed_plans=Count('plan__is_completed')) \
.values('num_of_completed_plans', 'id', 'date')
# Counting status=deferred Plans by Day
Day.objects \
.filter(plan__status='deferred') \
.annotate(num_of_deferred_plans=Count('plan__is_completed')) \
.values('num_of_deferred_plans', 'id', 'date')
如您在上面看到的,有3个查询。不知何故,我需要优化此代码,并在一个查询的帮助下获取值
模型
class Day(models.Model):
date = models.DateField(default=datetime.date.today, unique=True)
class Plan(models.Model):
title = models.CharField(max_length=255)
status = models.CharField(max_length=255, choices=PLAN_STATUSES, null=True, default='upcoming')
is_completed = models.BooleanField(default=False, null=True)
day = models.ForeignKey(Day, CASCADE, null=True)
有没有办法优化这3个查询并使用一个查询获取值?
慕田峪9158850
相关分类