我有初始查询集,我循环遍历
stats = {}
queryset = Item.objects.all()
for sub in Subject.objects.all():
stats[str(sub.id)] = queryset.filter(subjects=sub.id).count()
如果不经常点击数据库,我怎么能这样做?
答案 0 :(得分:5)
from django.db.models import Count
stats = Subject.objects.annotate(count=Count('item'))
现在每个统计信息对象都有count
字段:
stats[0].count
答案 1 :(得分:3)
Subject.objects.values('pk').annotate(total=Count('item'))