I could not do this with pure Django code, but this is the best I could do, depending as much as possible on the Django code instead of raw sql.
from django.db import connection from django.db.models import Count def get_average_count(klass, field_name): foo = klass.objects.values(field_name).annotate(countval=Count('id')) query = "SELECT AVG(subquery.countval) FROM (%s) subquery" % str(foo.query) cursor = connection.cursor() cursor.execute(query) return float(cursor.fetchone()[0])
This will execute the exact SQL statement that you said you want to generate. It is also completely independent of the SQL backend you are using and is fully reused (yay DRY) for all classes with the reverse ForeignKey or ManyToMany relationships.
If you really don't want to use raw SQL, another option is to calculate the average in Django:
from __future__ import division
You might want to check for any performance differences if you plan to have large databases in your database.
source share