I need to count lines in a subquery and here is my solution for sqlite.
class SQCount(Subquery):
"""Count lines in subquery"""
template = "(SELECT count(*) FROM (%(subquery)s) _count)"
output_field = models.IntegerField()
sub = MyModel.objects.filter(user=OuterRef(OuterRef('id'))).values('id')
qs = qs.annotate(count_total=SQCount(sub))
It works great for sqlite but not for MySQL (complains about Unknown column in 'where' clause). Any help appreciated.