Divide blogs according to year in list of queryset
I am building a blog app and I am trying to seperate blogs based on the year they were created. like :-
2022
First Blog
Second Blog
2021
Third Blog
Fifth Blog
It can be in list dictionary like :-
[
"2022": {
"title": "First Blog",
"title": "Second Blog",
},
"2021": {
"title": "Fifth Blog",
"title": "Second Blog",
}
]
models.py
class Blog(models.Model):
title = models.CharField(max_length=100, default='')
date = models.DateTimeField(auto_now_add=True)
views.py
def get_blogs(request):
blogs_by_year = Blog.objects.annotate(
year=TruncMonth('date')).annotate(
blogs=Count('title')).values("year", "blogs")
return blogs_by_year
But it is showing seperate results like
<QuerySet [{'year': datetime.datetime(2023, 1, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'blogs': 1}, {'year': datetime.datetime(2023, 1, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'blogs': 1}]>
But I am trying to seperate based on year.
Should I seperate blogs by year using for loop
and then filter according to year and append in list of dictionary ?
I have read the DateField truncation page but it didn't worked out.