`ValueError: This queryset contains a reference to an outer query and may
only be used in a subquery.`
```
first_unpaid_fee_schedule_instalment =
Subquery(FeeScheduleInstalment.objects \
.annotate(
total_balance = Subquery(
FeeInstalmentTransaction.objects.filter(
account_id=OuterRef(OuterRef('id')), # not
working: need grand-parent's id here
instalment__schedule=OuterRef('id'),
#working: parent's id
) \
.values('balance') \
.annotate(total_balance=Sum('balance')) \
.values('total_balance')
)
) \
.values('id')[:1]
)
fee_accounts_with_first_unpaid = FeeAccount.objects \
.annotate(
first_unpaid_schedule =
first_unpaid_fee_schedule_instalment,
)
```
--
Ticket URL: <https://code.djangoproject.com/ticket/31963>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* stage: Unreviewed => Accepted
Old description:
New description:
--
--
Ticket URL: <https://code.djangoproject.com/ticket/31963#comment:1>
* stage: Accepted => Unreviewed
Comment:
You should not accept your own tickets.
--
Ticket URL: <https://code.djangoproject.com/ticket/31963#comment:2>
* keywords: OuterRef, QuerySet, Django Filter, Annotation, Database, ORM
=> OuterRef, QuerySet, Django Filter, Annotation
* status: new => closed
* resolution: => worksforme
Old description:
New description:
Trying to access `FeeAccount` model's id using **OuterRef** in a **nested
subquery**, but **not immediate parent**. Throwing:
`ValueError: This queryset contains a reference to an outer query and may
only be used in a subquery.`
{{{
first_unpaid_fee_schedule_instalment = Subquery(
FeeScheduleInstalment.objects.annotate(
total_balance = Subquery(
FeeInstalmentTransaction.objects.filter(
account_id=OuterRef(OuterRef('id')), # not working: need
grand-parent's id here
instalment__schedule=OuterRef('id'), #working: parent's id
).values('balance').annotate(total_balance=Sum('balance')).values('total_balance')
),
).values('id')[:1]
)
fee_accounts_with_first_unpaid = FeeAccount.objects.annotate(
first_unpaid_schedule = first_unpaid_fee_schedule_instalment,
)
}}}
--
Comment:
The described example works for me.
--
Ticket URL: <https://code.djangoproject.com/ticket/31963#comment:3>