Django ORM:过滤以获取生日周在 n 天内的用户

Django ORM : Filter to get the users whose birthday week is in n days

提问人:Artory 提问时间:5/24/2023 更新时间:5/24/2023 访问量:60

问:

我正在尝试进行一个 django 查询,它应该给我生日周在 n 天内的用户。

我已经尝试使用 __week 运算符,但它没有按预期工作:

    now = timezone.now().date()
    first_day_of_next_week = (now + timedelta(days=(7 - now.weekday())))

    if now + relativedelta(days=n_days) == first_day_of_next_week:
        return qs.filter(birth_date__isnull=False, birth_date__week=first_day_of_next_week.strftime("%V"))

事实上,例如,如果用户出生于 24/06/1997,那么 24/06 在 1997 年和 2023 年不在同一周,所以它给了我意想不到的结果。

你能帮我解决这个问题吗?

python django 日期时间 orm

评论


答:

0赞 rahul.m 5/24/2023 #1

试试这个

范围滤波器 https://docs.djangoproject.com/en/4.2/ref/models/querysets/#range

import datetime
date = datetime.date.today()
start_week_date = date - datetime.timedelta(date.weekday())
end_week_date = start_week_date + datetime.timedelta(7)
qs = qs.filter(birth_date__range=[start_week, end_week])

它将获得当前周的记录

评论

1赞 Artory 5/24/2023
它不起作用,因为在我的示例中birth_date年份是 1997 年,而用于示例的日期具有当前年份
0赞 Artory 5/24/2023 #2

我终于设法找到了解决方案:

    now = timezone.now().date()
    first_day_of_next_week = (now + timedelta(days=(7 - now.weekday())))

    # If next week starts in n days
    if now + relativedelta(days=value) == first_day_of_next_week:

        next_week_days = []
        next_week_month = None

        next_week_days_month2 = []
        next_week_month2 = None

        # Store each day nbr of next week and the month number
        # If there are days from an other month in next week, store them separately
        for i in range(7):
            current_day = first_day_of_next_week + relativedelta(days=i)

            if current_day.month == first_day_of_next_week.month:
                next_week_days.append(current_day.day)
                next_week_month = current_day.month
            else:
                next_week_days_month2.append(current_day.day)
                next_week_month2 = current_day.month

        from django.db.models.functions import ExtractDay, ExtractMonth

        # Extract day and month of birth date
        # Compare them with the day and months of the next week
        users = qs.annotate(
            birth_date_day=ExtractDay('birth_date'),
            birth_date_month=ExtractMonth('birth_date')
        ).filter(
            Q(birth_date_day__in=next_week_days, birth_date_month=next_week_month) |
            Q(birth_date_day__in=next_week_days_month2, birth_date_month=next_week_month2)
        )

        return users

    return qs.none()