Вопрос

I have a query in SQLAlchemy:

weekly_schedule = WeeklyHour.query.filter(
    and_(
        WeeklyHour.start_time.in_(week_dates),
        WeeklyHour.end_time.in_(week_dates),
        WeeklyHour.employee == employee
        )
    ).all()

I am getting the dates of the current week like so:

today = datetime.datetime.today()
week_dates = [today + datetime.timedelta(days=i) for i in xrange(0 - today.weekday(), 7 - today.weekday())]

This returns a list of the current week in datetimes. Like so:

[datetime.date(2014, 4, 7), datetime.date(2014, 4, 8), datetime.date(2014, 4, 9), datetime.date(2014, 4, 10), datetime.date(2014, 4, 11), datetime.date(2014, 4, 12), datetime.date(2014, 4, 13)]

The problem is that the WeeklyHour is a datetime when the employee started and ended that day. And week_dates are a specific time set to now(). I will never get results because the time of the datetime won't match. All I really want to compare is the date portion of the datetime. My current solution (which works but is dumb) is to store separate dates of the datetime.

Это было полезно?

Решение

Rather than querying "in" all days of the week use the days as limits.

today = date.today()
start_of_week = today - timedelta(days=today.weekday())
start_of_following_week = start_of_week + timedelta(days=7)

weekly_schedule = WeeklyHour.query.filter(
    and_(
        WeeklyHour.start_time >= start_of_week,  # On or after Monday
        WeeklyHour.end_time < start_of_following_week, # Before next Monday
        WeeklyHour.employee == employee
        )
    ).all()
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top