I'm having problems using annotate() with OuterRef
in Django 1.11 subqueries. Example models:
class A(models.Model):
name = models.CharField(max_length=50)
class B(models.Model):
a = models.ForeignKey(A)
Now a query with a subquery (that does not really make any sense but illustrates my problem):
A.objects.all().annotate(
s=Subquery(
B.objects.all().annotate(
n=OuterRef('name')
).values('n')[:1],
output_field=CharField()
)
)
This gives the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "myapp/models.py", line 25, in a
n=OuterRef('name')
File ".virtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 948, in annotate
if alias in annotations and annotation.contains_aggregate:
AttributeError: 'ResolvedOuterRef' object has no attribute 'contains_aggregate'
Is it not possible to annotate a subquery based on an OuterRef?
Update #1
Found a workaround for this that will allow me to move forward for now, but it's not nice.
class RawCol(Expression):
def __init__(self, model, field_name, output_field=None):
field = model._meta.get_field(field_name)
self.table = model._meta.db_table
self.column = field.column
super().__init__(output_field=output_field)
def as_sql(self, compiler, connection):
sql = f'"{self.table}"."{self.column}"'
return sql, []
Changing OuterRef
to use the custom expression
A.objects.all().annotate(
s=Subquery(
B.objects.all().annotate(
n=RawCol(A, 'name')
).values('n')[:1],
output_field=CharField()
)
)
Yields
SELECT "myapp_a"."id",
"myapp_a"."name",
(SELECT "myapp_a"."name" AS "n"
FROM "myapp_b" U0 LIMIT 1) AS "s"
FROM "myapp_a"