2

I have done annotation on Student objects so that it has two new fields -> project_count and member_count as follows:

top_students = Student.objects.annotate(project_count= Count('project'), member_count = Count('member_student'))

I would now like to perform sum of these two values at database level. i.e return something like:

total_count = project_count + member_count

I have tried using .extra() like this:

top_students = Student.objects.annotate(project_count= Count('project'), member_count = Count('member_student')).extra( select = {'total_count': 'project_count + member_count'}, order_by = ('total_count', ) )

But it shows an error : OperationalError: (1054, "Unknown column 'project_count' in 'field list'")

Should I write raw SQL or is there any other way to do this:

Sudip Kafle
  • 4,286
  • 5
  • 36
  • 49
  • 3
    Why specifically does it need to be done at database level? Simple addition can just as well be done in Python, surely. It's only for operations across whole sets of data - such as aggregation itself - that doing it in the db is more efficient. – Daniel Roseman Jul 06 '14 at 08:58
  • 1
    @DanielRoseman I need to sort the data based on the total_count and return only the top 3 items. If its not done at database level, it would be a lot of overhead. – Sudip Kafle Jul 06 '14 at 09:13

0 Answers0