Answer the question
In order to leave comments, you need to log in
Grouping articles by month in django?
There are articles, you need to group them by month. That is, display a list of only those months in which there are articles, then after switching to this month, all articles of this month are opened. Should I do it in views or in template? And how to do it?
Answer the question
In order to leave comments, you need to log in
Or without CBV
from django.shortcuts import render
from django.db.models import Count
from django.db.models.functions import TruncMonth
from .models import Article
def group_by_month(request):
groups = Article.objects
.annotate(month=TruncMonth('publication_date')) # Извлекаем месяц из даты
.values('month') # Группируем по месяцам
.annotate(c=Count('id')) # Количество статей в месяце
return render(request, 'monthes.html', {'monthes': groups})
def articles_in_month(request, month):
articles = Article.objects.filter(publication_date__month=month)
return render(request, 'articles', {'articles': articles})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question