latest_update = BillHistory.objects.filter(
bill=OuterRef('id')).order_by('-occurred_datetime')
user_bills = Bill.objects.only(
"bill_number", "short_title").filter(session='2023-2024').filter(
Q(users__archived=False)
& Q(users__user=user)).annotate(
priority=F('users__billuserpriority__priority'),
position=F('users__billuserposition__position'),
latest_update_on=Max('histories__occurred_datetime'),
committee_names=Subquery(
latest_update.values('committee_names__name')[:1]),
latest_update_status=Subquery(
latest_update.values('status')[:1])).prefetch_related(
'users__clients__client',
'users__pillars__pillar').order_by(
Func(F('bill_number'), function='alphanum'))
prefetch_related works wonders here. What is the more performant query to access the prefetched objects? At the moment, I am accessing a client object like so in the template: bill.users.all → users.clients.all → client. Although I am able to filter first by user and then by clients for that user, this is resulting in duplicate and similar queries. Thank you.