You can use the extra query method to select additional data from the database table.
This is an example that works with MySql:
Person.objects.extra(select={ 'datediff': 'ABS(DATEDIFF(date, NOW()))'}).order_by('datediff')
DATEDIFF - returns the difference in days after two dates, ABS - returns the absolute value. There is a different syntax for sqlite, see this answer .
EDIT: use current year
Person.objects.extra(select={ 'datediff': "ABS(DATEDIFF(CONCAT(YEAR(now()), '-', MONTH(date), '-', DAY(date)), NOW()))"} ).order_by('datediff')
EDIT 2: optimized *
from datetime import date dayofyear = int(date.today().strftime("%j")) datediff = 'LEAST(ABS(DAYOFYEAR(date) - %d), ABS((366 - %d + DAYOFYEAR(date))) MOD 366)' % ( dayofyear, dayofyear ) Person.objects.extra(select={'datediff': datediff}).order_by('datediff')
EDIT 3: nearest date after date (today)
from datetime import date dayofyear = int(date.today().strftime("%j")) datediff = '(DAYOFYEAR(date) - %d + 365) MOD 365' % ( dayofyear ) Persion.objects.extra(select={'datediff': datediff}).order_by('datediff')
bmihelac
source share