Filter on datetime closest to the given datetime

Just change Pavlel's answer to:

def get_closest_to_dt(qs, dt):
    greater = qs.filter(dt__gte=dt).order_by("dt").first()
    less = qs.filter(dt__lte=dt).order_by("-dt").first()

    if greater and less:
        return greater if abs(greater.dt - dt) < abs(less.dt - dt) else less
    else:
        return greater or less

You can get it with two queries and some logic:

The idea is to find one object immediately following and one immediately preceding the target datetime and to return one of them:

# this method is on the model's manager
def get_closest_to(self, target)
    closest_greater_qs = self.filter(dt__gt=target).order_by('dt')
    closest_less_qs    = self.filter(dt__lt=target).order_by('-dt')

    try:
        try:
            closest_greater = closest_greater_qs[0]
        except IndexError:
            return closest_less_qs[0]

        try:
            closest_less = closest_less_qs[0]
        except IndexError:
            return closest_greater_qs[0]
    except IndexError:
        raise self.model.DoesNotExist("There is no closest object"
                                      " because there are no objects.")

    if closest_greater.dt - target > target - closest_less.dt:
        return closest_less
    else:
        return closest_greater

To get it with one query, you have to drop out of ORM to raw SQL.

Tags:

Django