Skip to content

Instantly share code, notes, and snippets.

@hwshim0810
Created March 15, 2018 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hwshim0810/3963397ed1b7e1fda37355659abd0b3b to your computer and use it in GitHub Desktop.
Save hwshim0810/3963397ed1b7e1fda37355659abd0b3b to your computer and use it in GitHub Desktop.
Django queryset filter : group by max limit 1
"""
class SampleCategoryModel
id = primary
class SamplePostModel
category = foreignkey(SampleCategoryModel)
created_at = datetimefield
"""
from django.db.models import Max
query_set = SamplePostModel.objects.all()
condition = query_set.values('category').annotate(last_row_at=Max('created_at'))
query_set = query_set.filter(created_at__in=condition.values('last_row_at'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment