I have a huge list of lessons ordered by the date. I want to include paginator so it would always set default page on a current date(if such lessons exists, and if not the nearest future lessons).Is it even possible to do?
from django.contrib.auth.models import Lesson
from django.core.paginator import Paginator
lesson_list = Lesson.objects.all().order_by('datetime')
paginator = Paginator(user_list, 10)
You can annotate your QuerySet with a conditional expression based on whether or not the
Lessonis today, and then use that annotation to sort your QuerySet..date()to get a date object from the datetime object.annotate()the QuerySet with a field namedlesson_today.lesson_todayis a booleanCase()whereLesson.datetimehas a year, month and day that matches the current date. Use the__datesubscript to ensure we're not trying to match on the hour, minute and second components of theDateTimeField.-lesson_todayfirst means that objects wherelesson_today=Trueare sorted first. The remaining objects are then sorted in reverse chronological order (e.g. future lessons).