[Django]-Django: Filtering datetime field by *only* the year value?

44👍

Either construct custom SQL or use

date_list = Note.objects.all().dates('created', 'year')

for years in date_list:
    Note.objects.filter(created__year = years.year)

This is the way it is done in date based generic views.

3👍

You can use django.views.generic.date_based.archive_year or use year field lookup.

1👍

We can improve the filter using a list of years, then check if the year of creation is on that.

With that list, the database will be called once one time, because the Note.objects.filter will runs outside the for loop.

Something like this:

notes = Note.objects.all().dates('created', 'year')
years = [note.year for note in notes]

Note.objects.filter(created__year__in = years)

Leave a comment