22👍
✅
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.
7👍
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
4👍
I’d like to complete Pavel’s answer, as:
dt__gte
dt__lte
should be used instead.
Filtering when providing the exact date won’t work properly otherwise.
- Django admin inline many to many custom fields
- Django annotate and count: how to filter the ones to include in count
- Making Django Readonly ForeignKey Field in Admin Render as a Link
1👍
Generic implementation of the above versions to use with arbitrary models.
def get_closest(
*,
qs: models.QuerySet,
datetime_field: str,
target_datetime: Union[datetime.datetime, datetime.date],
) -> models.Model:
greater = qs.filter(**{
f'{datetime_field}__gte': target_datetime,
}).order_by(datetime_field).first()
less = qs.filter(**{
f'{datetime_field}__lte': target_datetime,
}).order_by(f'-{datetime_field}').first()
if greater and less:
greater_datetime = getattr(greater, datetime_field)
less_datetime = getattr(less, datetime_field)
return greater if abs(greater_datetime - target_datetime) < abs(less_datetime - target_datetime) else less
else:
return greater or less
Source:stackexchange.com