Here's an isolated ORM query:
Purpose.objects.annotate(
conversation_count=SubqueryCount(
Conversation.objects.filter(goal_slugs__contains=[OuterRef("slug")]).values("id")
)
)
Where SubqueryCount is:
from django.db.models import IntegerField
from django.db.models.expressions import Subquery
class SubqueryCount(Subquery):
template = "(SELECT count(*) FROM (%(subquery)s) _count)"
output_field = IntegerField()
When that query is run, the following sql is used (via djdt explain):
SELECT
"taxonomy_purpose"."id",
"taxonomy_purpose"."slug",
(
SELECT count(*)
FROM (
SELECT U0."id"
FROM "conversations_conversation" U0
WHERE U0."goal_slugs" @> ARRAY['ResolvedOuterRef(slug)']::varchar(100)[]
) _count
) AS "conversation_count"
FROM "taxonomy_purpose"
Note the ResolvedOuterRef(slug) injected into the ARRAY lookup as a string. Am I doing something wrong, or should I report this as a bug? If this is a bug, is there a known workaround (maybe creating a custom OuterRef class)?