[Django]-Django annotate multiple objects based on multiple fields on a M2M relationship

0👍

You forgot to set OuterRef https://docs.djangoproject.com/en/2.2/ref/models/expressions/

b_qs = B.objects.filter(a=OuterRef('pk')).order_by('-created_timestamp')
a_qs = A.objects.filter(id__in=ids).annotate(oldest_name=Subquery(b_qs.values('name')[:1])
result = list(a_qs)

Leave a comment