1👍
✅
You can work with subqueries:
from django.db.models import OuterRef, Subquery
Item.objects.annotate(
prix_x1=Subquery(
Prix_x1.objects.filter(
item=OuterRef('pk')
).values('prix').order_by('-saved_at')[:1]
),
prix_x10=Subquery(
Prix_x10.objects.filter(
item=OuterRef('pk')
).values('prix').order_by('-saved_at')[:1]
)
)
The Item
s that arise from this queryset will have two extra attribute .prix_x1
and .prix_x10
that contain the prix
for the last Prix_x1
and Prix_x10
records related to that item.
Source:stackexchange.com