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
Lesson
is 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_today
is a booleanCase()
whereLesson.datetime
has a year, month and day that matches the current date. Use the__date
subscript to ensure we're not trying to match on the hour, minute and second components of theDateTimeField
.-lesson_today
first means that objects wherelesson_today=True
are sorted first. The remaining objects are then sorted in reverse chronological order (e.g. future lessons).