Django Total Children Count across query

566 views Asked by At

I'm trying to get a total count of children from a set of parent objects. To explain this better. I have a set of SOW, which belong to a Year Group. Each SOW has a number of lessons. I want a total of lessons per Year Group. I'm currently getting the lessons per SOW count with a filter

@register.simple_tag
def lesson_sow_count(value):
  count = Lesson.objects.select_related().filter(schemeofwork_id=value).count()
  return count

Is there an easy way to do this. The view method is already splitting SOWs into year groups and sorting them so I can present them in tabs so I'm stuck on how to alter this.

def index(request):
    allsow = dict()
    allsow['Year 7'] = SchemeOfWork.objects.order_by('order').filter(yeargroup=7)
    allsow['Year 8'] = SchemeOfWork.objects.order_by('order').filter(yeargroup=8)
    allsow['Year 9'] = SchemeOfWork.objects.order_by('order').filter(yeargroup=9)
    template = loader.get_template('planner/index.html')
    context = RequestContext(request, {
        'allsow': sorted(allsow.iteritems()),
    })
    return HttpResponse(template.render(context)

Thanks for your time and efforts in any answer

Chris

1

There are 1 answers

1
BriceP On BEST ANSWER

I'm not sure about what it is all about, but it seems that you could use a simple query :

allsow = SchemeOfWork.objects.filter(yeargroup_gte=7, yeargroup_lte=9).order_by('yeargroup', 'order')

Then, you would use annotate like in the example given here to make the count : https://docs.djangoproject.com/en/1.8/ref/models/querysets/#annotate

But as I didn't really get what you're doing, I'm not sure that's the answer...