django - Filter over queryset with a loop -


i have inital queryset , loop on this

stats = {} queryset = item.objects.all() sub in subject.objects.all():         stats[str(sub.id)] = queryset.filter(subjects=sub.id).count() 

how can without hit db often?

look django aggregation:

from django.db.models import count  stats = subject.objects.annotate(count=count('item')) 

now each stats object have count field:

stats[0].count 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -