I have two models
town = models.CharField()
bakery = models.ForeignKey(Bakery)
baked_at = models.DateTimeField()
As far as I know, there is no one-step way of doing this in Django ORM.
But you can split it in two queries:
bakeries = Bakery.objects.annotate(hottest_cake_baked_at=Max('cake__baked_at')) hottest_cakes = Cake.objects.filter(baked_at__in=[b.hottest_cake_baked_at for b in bakeries])
If id's of cakes are progressing along with bake_at timestamps, you can simplify and disambiguate the above code (in case two cakes arrives at the same time you can get both of them):
hottest_cake_ids = Bakery.objects.annotate(hottest_cake_id=Max('cake__id')).values_list('hottest_cake_id', flat=True) hottest_cakes = Cake.objects.filter(id__in=hottest_cake_ids)
BTW credits for this goes to Daniel Roseman, who once answered similar question of mine:
If the above method is too slow, then I know also second method - you can write custom SQL producing only those Cakes, that are hottest in relevant Bakeries, define it as database VIEW, and then write unmanaged Django model for it. It's also mentioned in the above django-users thread. Direct link to the original concept is here:
Hope this helps.