I have a problem with subquery count in Python Django...
Query MySQL:
SELECT usuario.name, COUNT(*) AS Groups,(
SELECT COUNT(*)
FROM group
WHERE group.user_id=user.id and state = 'on going') AS Started
FROM user
INNER JOIN group
ON (user.id=group.user_id)
WHERE user.rol = 'Provider'
GROUP BY group.user_id
ORDER BY Groups desc;
Views:
connected_query= GroupModel.objects.values(
'usuario__name').filter(
user__rol='PROVIDER'.lower(), status='ON_GOING'.lower()).annotate(
started=Count('user'))
totals_query = GroupModel.objects.values(
provider=Concat('user__name', Value(' '), 'user__surname')).annotate(
totals=Count('user'),connected=Subquery(connected_query.values('started')[:1])).order_by(
'-connected')
First query return:
<QuerySet [{'user__name': 'James', 'started': 3}, {'user__name': 'John', 'started': 2}, {'user__name': 'Frank', 'started': 2}, {'user__name': 'Sara', 'started': 1}]>
While second query return:
<QuerySet [{'user__name': 'James', 'totals': 10, 'started': 3}, {'user__name': 'John', 'totals': 10, 'started': 3}, {'user__name': 'Frank', 'totals': 12, 'started': 3}, {'user__name': 'Sara', 'totals': 9, 'started': 3}]>
I need the query to return the following:
<QuerySet [{'user__name': 'James', 'totals': 10, 'started': 3}, {'user__name': 'John', 'totals': 10, 'started': 2}, {'user__name': 'Frank', 'totals': 12, 'started': 2}, {'user__name': 'Sara', 'totals': 9, 'started': 1}]>
The problem is that the second query, always return 3, which are the connected that the user 'James', if in subquery I remove [:1] python gives me the following error: django.db.utils.OperationalError: (1241, 'Operand should contain 1 column(s)')
I don't know where to continue, I'm a bit desperate, any help is good