Python Django注释聚合速度
我使用以下注释在数据库中生成相关对象的计数:Python Django注释聚合速度,python,django,Python,Django,我使用以下注释在数据库中生成相关对象的计数: challenges = Challenge.objects.annotate( solve_count=Count('solves', filter=Q(solves__correct=True)), unlock_time_surpassed=Case( When(release_time__lte=timezone.now(), then=Value(True)), default=Value(F
challenges = Challenge.objects.annotate(
solve_count=Count('solves', filter=Q(solves__correct=True)),
unlock_time_surpassed=Case(
When(release_time__lte=timezone.now(), then=Value(True)),
default=Value(False),
output_field=models.BooleanField(),
),
votes_positive=Count("votes", filter=Q(votes__positive=True), distinct=True),
votes_negative=Count("votes", filter=Q(votes__positive=False), distinct=True),
)
这生成的查询大约需要2000毫秒才能执行,需要1000个挑战和100万个解决方案。
如果我用solve\u count=Value(0,output\u field=models.IntegerField())替换solve\u count=count('solves',filter=Q(solves\u correct=True)),
,查询所花费的时间从2000ms变为50ms(但显然在这个过程中,求解计数丢失了)
我能做些什么来提高计数操作的性能吗?挑战和解决表的索引是什么?确保解决。挑战id
(或您所称的)已被索引。但在这种情况下,我喜欢做的一件事就是自己编写原始SQL并比较执行时间,以便了解。你试过了吗?