[Answered ]-Get last record by date for multiple table with many-to-one relationship

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 Items 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.

Leave a comment