1👍
✅
Seems like what you need is a GROUP BY statement, and unfortunately django doesn’t offer that – see this question Django: Group by?
Personally I’d probably approach it from a different angle, and use a Product queryset instead. You can filter on offer fields and order by annotated priority/rpl values, then for each product you’d need to retrieve the offer details separately. It means an extra query for each row, but it might be the best you can do. Eg:
Product.objects.filter(offer__...=...) \
.annotate(priority=models.Max('offer__contract__priority'),
rpl=models.Max('offer__contract__rpl')) \
.order_by('-priority', '-rpl')
👤Greg
Source:stackexchange.com