This is what I want Django to generate in SQL:
select avg(subquery.countval) from (
select count(something) countval,user_id from foo group by user_id
) subquery
How I think this should work with Django based on the Annotated aggregation documentation:
Foo.objects.all().values('user_id').\
annotate(countval=Count('id')).\
aggregate(Avg('countval'))
The problem is that Django 4.x doesn't generate the correct query. You get something like:
SELECT FROM (SELECT foo.user_id as user_id,COUNT(foo.id)
AS countval from foo
group by foo.user_id)
Any ideas? I debugged through the source but it isn't obvious what is going wrong.