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

11👍

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.

2👍

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

To filter on Max date:

ModelClass.objects.annotate(max_date=Max('pubdate')).filter(pubdate=F('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.

2👍

Throoze try this…

 queryset=Expo.objects.annotate(max_date=Max('date'))
 queryset1=queryset.values().filter(date__gte=F('max_date'))

Leave a comment