xwild
xwild

Reputation: 1144

Django, select a maximum from annotated maximums (maximum from a few fields)

I have a question about django annotation methods: is it possible to calculate "maximum_discount" of these 3 particular discounts (and sort by this "maximum_discount")?

Product.objects\
   .annotate(
        product_discount=Max('discounts__amount'),
        category_discount=Max('category__discounts__amount'),
        brand_discount=Max('brand__discounts__amount')
    )

Upvotes: 4

Views: 73

Answers (2)

Vadim Zabolotniy
Vadim Zabolotniy

Reputation: 387

According to Django documentation you can do next thing:

from django.db.models.functions import Greatest
Product.objects.annotate(max_discount=Greatest('discounts__amount', 'brand__discounts__amount', 'category__discounts__amount'))

But note that this appear in Django 1.9.

Upvotes: 1

Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5611

Try something like this:

max_discount = max(value for key, value in Product.objects\
   .annotate(  # maybe 'aggregate'?
        product_discount=Max('discounts__amount'),
        category_discount=Max('category__discounts__amount'),
        brand_discount=Max('brand__discounts__amount')
    )
)

Upvotes: 1

Related Questions