How to sort my Django request set by today?

Does anyone know how I can sort (at this moment) my django request set against today's date?

class Person(models.Model): name = models.CharField(max_length=50) date = models.DateField() 

My goal is to specify names and dates. At the top of the list will be a record with a date that is closest to today's date (day / month).

+7
source share
2 answers

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') 
+6
source

If you want to sort by date, you can order as: .order_by('date') in the query for results.

I am not sure if this answers your question. If you want to select only Persons with a date of today, you can use:

 import datetime now = datetime.datetime.now() persons_with_date_today = Person.objects.filter(date=now) 
0
source

All Articles