[Answer]-Next upcoming date model object ignoring past dates

1👍

Since I’m a little old school, it usually helps me to think of such problems as an SQL query. In your case this would be

SELECT * FROM app_raidsession rs
    WHERE rs.scheduled >= now()
    ORDER BY rs.scheduled
    LIMIT 1

This gives you the next scheduled raid.

In django ORM, you should be able to translate this more or less straightforward to:

from django.utils.timezone import now

# first() returns None if the result is empty
next_raid = models.RaidSession.objects \
    .filter(scheduled__gte=now()) \
    .order_by('scheduled') \
    .first()

If the duration is relevant, you will need an F-expression:

from django.db.models import F

next_raid = models.RaidSession.objects \
    .filter(scheduled__gte=now() - F('duration')) \
    .order_by('scheduled') \
    .first()
👤dhke

Leave a comment