﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31415	QuerySet crashes when nested OuterRef is combined with an operator or used in function.	Ben Nace	Hasan Ramezani	"Given the following contrived set of models and the latest Django 3.0.5:

{{{
class Node(models.Model):
    steplen = 4
    path = models.CharField(max_length=100)


class NodeAttribute(models.Model):
    node = models.ForeignKey(Node, on_delete=models.CASCADE)
    attribute_name = models.CharField(max_length=64)
    attribute_value = models.CharField(max_length=64)


class Entity(models.Model):
    name = models.CharField(max_length=64)
    age = models.IntegerField()


class EntityNode(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE)
    node = models.ForeignKey(Node, on_delete=models.CASCADE)
    role = models.CharField(max_length=64)
}}}

The query

{{{
NodeAttribute.objects.annotate(
    test=Subquery(Entity.objects.filter(
        entitynode__node__nodeattribute__attribute_name=OuterRef('attribute_name'), 
        name=Subquery(EntityNode.objects.filter(
            node__path=Left(OuterRef(OuterRef('node__path')), Node.steplen * 2)
        ).values('entity__name')[:1])
    ).values('age')[:1])
)
}}}
produces the exception ""AttributeError: 'OuterRef' object has no attribute 'relabeled_clone'.""

The problem is with using nested OuterRefs as a parameter to Left. I have not had any trouble with using a single OuterRef with SQL functions, but trying to go up two levels with nested OuterRefs does not appear to work. Please note that the above models and query are for illustrative purposes only and represent the simplest example of the problem I could come up with."	Bug	closed	Database layer (models, ORM)	dev	Normal	fixed		Simon Charette	Accepted	1	0	0	0	1	0
