Skip to content

Instantly share code, notes, and snippets.

@mtigas
Forked from ryanpitts/gist:1304725
Created October 21, 2011 19:44
Show Gist options
  • Save mtigas/1304751 to your computer and use it in GitHub Desktop.
Save mtigas/1304751 to your computer and use it in GitHub Desktop.
GROUP BY and Select MAX from each group in Django, 2 queries
'''
given a Model with:
category = models.CharField(max_length=32, choices=CATEGORY_CHOICES)
pubdate = models.DateTimeField(default=datetime.now)
<other fields>
Fetch the item from each category with the latest pubdate.
'''
model_max_set = Model.objects.values('category').annotate(max_pubdate=Max('pubdate')).order_by()
# THE "ONE LINE BECAUSE FUNCTIONAL PROGRAMMING IS AWESOME BLAH BLAH BLAH" EDITION
# kudos to tkaemming
model_set = Model.objects.filter( reduce(lambda a,b:a|b, [(Q(category__exact=pair['category']) & Q(pubdate=pair['max_pubdate'])) for pair in model_max_set ]) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment