如何编写一个根据当前日期设置默认页面的分页器?

How to write a paginator which would set a default page depending on the current date?

我有一长串按日期排序的课程。我想包含分页器,以便它始终在当前日期设置默认页面(如果存在此类课程,如果不是最近的未来课程)。甚至可以这样做吗?

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)

您可以根据 Lesson 是否是今天来用 conditional expression 注释您的 QuerySet,然后使用该注释对您的 QuerySet 进行排序。

from datetime import date  # for typing
from django.db.models import BooleanField, Case, Value, When
from django.utils import timezone

current_date: date = timezone.now().date()

lesson_list = Lesson.objects.annotate(
    lesson_today=Case(
        When(datetime__date=current_date, then=Value(True)),
        default=Value(False),
        output_field=BooleanField()
    )
).order_by('-lesson_today', '-datetime')
  • 通过使用 Django 的 built-in timezone utility. Use .date() 从日期时间对象中获取日期对象来获取当前日期时间。
  • annotate() 带有名为 lesson_today.
  • 字段的 QuerySet
  • lesson_today 的值是布尔值 Case() where Lesson.datetime has a year, month and day that matches the current date. Use the __date 下标,以确保我们不会尝试匹配 DateTimeField.[=33 的小时、分钟和秒组件=]
  • -lesson_today 先排序意味着 lesson_today=True 的对象首先排序。然后将剩余的对象按时间倒序排序(例如,未来的课程)。