EDIT: this solution works, but Ross Lote is cleaner
Here's how I did it using Jango Aggregation :
from django.db.models import Max actions_id = Action.objects.all().values('product_id') \ .annotate(action_id=Max('id')) \ .order_by('-action_id')[:10] \ .values_list('action_id', flat=True) result = Action.objects.filter(id__in=actions_id).order_by('-created_at')
By setting values('product_id') , we make the group on product_id .
With annotate() we can use order_by only for the fields used in values() or annotate() . Since the created_at field is now automatically set for each action, ordering by created_at is the same as ordering by id , using annotate(action_id=Max('id')).order_by('-action_id') right way.
Finnaly, we just need to chop our request [:10]
Hope this helps.
Charlesthk
source share