Django ORM:筛选出生日周在n天内的用户

siv3szwd  于 2023-05-30  发布在  Go
关注(0)|答案(2)|浏览(146)

我正在尝试做一个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"))

事实上,例如,如果用户出生于1997年6月24日,那么24/06与1997年的星期nbr和2023年的星期nbr不同,所以它给了我意想不到的结果。
你能帮我吗?

ecr0jaav

ecr0jaav1#

试试这个
范围过滤器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])

它将获取当前周记录

xpcnnkqh

xpcnnkqh2#

我终于找到了解决办法:

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

相关问题