[Solved]-Django – Filter a queryset by Max(date) year


Performing statement in a single query is no guarantee to improve performance, this is easy to understand if you try to write an agnostic RDBMS brand SQL single sentence for yours requirements. Also, you lost in readability.

In my opinion, you can see and elegant solution in this approach:

  1. Get last Expo by date .
  2. Do a simple filter query.

For your code:

max_year = Expo.objects.latest('date').date.year
expos = Expo.objects.filter(date__year=max_year)

Remember you can cache max_year, also create a DESC index over date can helps.


Here is how you can do something using a combination of Annotation and F object

To filter on Max date:


To filter on the year of Max date:

max_date = ModelClass.objects.latest("pubdate").pubdate
published_objs = ModelClass.objects.filter(pubdate__year=max_date.year)

There does not seem to be a way to filter on Max(date.year) in a single query. And as mentioned by @danihp, even a single query is not a guarantee of performance.


Throoze try this…


Leave a comment