def add_team_count(topics, course_id):
 topic_ids = [topic['id'] for topic in topics]
 teams_per_topic = CourseTeam.objects.filter(course_id=course_id, topic_id__in=topic_ids).values('topic_id').annotate(team_count=Count('topic_id'))
 topics_to_team_count = {d['topic_id']: d['team_count'] for d in teams_per_topic}
 for topic in topics:
  topic['team_count'] = topics_to_team_count.get(topic['id'], 0)

def add_team_count ( topics , course_id ) : topic_ids = [ topic [ 'id' ] for topic in topics ] teams_per_topic = CourseTeam . objects . filter ( course_id = course_id , topic_id__in = topic_ids ) . values ( 'topic_id' ) . annotate ( team_count = Count ( 'topic_id' ) ) topics_to_team_count = { d [ 'topic_id' ] : d [ 'team_count' ] for d in teams_per_topic } for topic in topics : topic [ 'team_count' ] = topics_to_team_count . get ( topic [ 'id' ] , 0 )
helper method to add team_count for a list of topics .