Opened 4 years ago

Closed 4 years ago

#31963 closed Bug (worksforme)

Nested OuterRef not woking to access grandparent's ID.

Reported by: Ashish Kulkarni Owned by: nobody
Component: Database layer (models, ORM) Version: 2.2
Severity: Normal Keywords: OuterRef, QuerySet, Django Filter, Annotation
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Mariusz Felisiak)

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,
)

Change History (3)

comment:1 by Ashish Kulkarni, 4 years ago

Description: modified (diff)
Triage Stage: UnreviewedAccepted

comment:2 by Mariusz Felisiak, 4 years ago

Triage Stage: AcceptedUnreviewed

You should not accept your own tickets.

comment:3 by Mariusz Felisiak, 4 years ago

Description: modified (diff)
Keywords: Database ORM removed
Resolution: worksforme
Status: newclosed
Summary: Django: Nested OuterRef not woking to access grandparent's IDNested OuterRef not woking to access grandparent's ID.

The described example works for me.

Note: See TracTickets for help on using tickets.
Back to Top