2015-05-31 80 views

回答

1

嘗試是這樣的:

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') 
    ) 
) 
+0

這裏的每個折扣都是GenericRelations,因此我必須爲產品,類別,品牌選擇折扣,然後從這些折扣中選擇最大值,然後按它們排序(甚至更多 - 將此計算的折扣應用於價格) 。 例如: 產品6 :: 5.00 :: 20.00 :: 25.00 - > 25.00 所以我需要做一個查詢集.. – xwild

+1

我擔心它遠遠落後於Django的queryset可能性。也許你應該嘗試原始查詢。 –

1

根據Django documentation你可以做的下一件事:

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

但請注意,這出現在Django 1.9。