Django, select maximum from annotated highs (maximum from several fields)

I have a question about django annotation methods: can I calculate the "maximum_discount" of these 3 specific 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')
    )
+4
source share
2 answers

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')
    )
)
+1
source

According to the Django documentation you can do the following:

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 is displayed in Django 1.9.

+1
source

All Articles