D
D
Dauren S2016-10-30 02:38:53
Django
Dauren S, 2016-10-30 02:38:53

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

2 answer(s)
S
Sergey Gornostaev, 2016-10-30
@dauren101

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})

Y
Yuri, 2016-10-30
@Ba1t

Generic date views
Select articles in the view, display them as needed in the template.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question