[Answered ]-Django ORM – How to get max price and the associated date

1πŸ‘

βœ…

It might be better to work with a QuerySet with Product as the main model, so:

from django.db.models import Max

Product.objects.annotate(max_price=Max('price__price'))

that way you retrieve Product objects with an extra attribute .max_price, but it still functions like a Product object, so you can follow ForeignKeys, etc.

You can obtain the modification date by using a subquery:

from django.db.models import F, Max, OuterRef, Subquery


def get_max_price_for_product(request):
    Product.objects.annotate(
        max_price=Max('price__price'),
        max_price_date=Subquery(
            Price.objects.filter(product_id=OuterRef('pk'))
            .order_by(F('price').desc(nulls_last=True))
            .values('date_seen')[:1]
        ),
    )
    context = {'max_price_list': max_price_list}
    return render(request, 'prices/max_list.html', context)

This will retrieve the date_seen for the largest price.

Leave a comment