我有初始查询集,我循环这个
stats = {}
queryset = Item.objects.all()
for sub in Subject.objects.all():
stats[str(sub.id)] = queryset.filter(subjects=sub.id).count()
我怎么能做到这一点而不经常打数据库?
我有初始查询集,我循环这个
stats = {}
queryset = Item.objects.all()
for sub in Subject.objects.all():
stats[str(sub.id)] = queryset.filter(subjects=sub.id).count()
我怎么能做到这一点而不经常打数据库?
寻找django 聚合:
from django.db.models import Count
stats = Subject.objects.annotate(count=Count('item'))
现在每个 stats 对象都会有count
字段:
stats[0].count
Subject.objects.values('pk').annotate(total=Count('item'))