#views.py
queryset = User.objects.all()
queryset = queryset.annotate(
request_ids=ArrayAgg("requests__id")
)
unread_messages = Request.objects.filter(
pk__in=OuterRef("request_ids")
)
queryset = queryset.annotate(
unread_messages=Coalesce(Subquery(unread_messages), 0)
)
I want to achieve something like this in SQL:
WITH user_requests AS (
SELECT
uchat_user.username,
Array_Agg(uchat_request.id) AS request_ids
FROM uchat_user
LEFT JOIN uchat_request ON uchat_request.refugee_id = uchat_user.id
GROUP BY uchat_user.username
)
SELECT
*,
(
SELECT COUNT(*) FROM uchat_request WHERE uchat_request.id IN (SELECT unnest(user_requests.request_ids))
) AS total_requests
FROM user_requests
However I get this error (table might be different but the overall the exception is like this):
operator does not exist: bigint = bigint[]
LINE 1: ...efugee_id" FROM "uchat_request" U0 HAVING U0."id" IN (ARRAY_...
^
HINT: No operator matches the given name and argument types. You might need to add explicit type casts.
Could you please help with that?