#31963: Nested OuterRef not woking to access grandparent's ID.
-------------------------------------+-------------------------------------
Reporter: Ashish Kulkarni | Owner: nobody
Type: Bug | Status: closed
Component: Database layer | Version: 2.2
(models, ORM) | Resolution:
Severity: Normal | worksforme
Keywords: OuterRef, QuerySet, | Triage Stage:
Django Filter, Annotation | Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by felixxm):
* keywords: OuterRef, QuerySet, Django Filter, Annotation, Database, ORM
=> OuterRef, QuerySet, Django Filter, Annotation
* status: new => closed
* resolution: => worksforme
Old 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,
> )
> }}}
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>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/070.aa360fef729cbb7036361a0d7bbcb661%40djangoproject.com.