[Answered ]-Django: Return id of maximum value where grouped by foreign key

1👍

✅

You can make use of a Subquery expression [Django-doc] and work with:

from django.db.models import OuterRef, Subquery

BookingModel.objects.annotate(
    latest_component_id=Subquery(BookingComponentModel.objects.filter(
        booking_id=OuterRef('pk'), status='In Progress', component_type='Soak'
    ).values('pk').order_by('-order')[:1])
)

The BookingModel objects that arise from this queryset will have an extra attribute latest_component_id that will contain the primary key of the latest BookingComponentModel with as status 'In Progress', and as component_type 'Soak'.

Leave a comment