Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort my Django Query Set against today date?

Tags:

django

Does anyone know how I can sort (in this instance date) my django query set against todays date ?

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

My goal is to list the name and date entries. At the top of the list will be the entry with the date that is closest to todays date (day/month).

like image 655
felix001 Avatar asked Apr 09 '13 20:04

felix001


People also ask

What is Order_by in Django?

Django order by lets you specify how your query results should be ordered. Here's an example where we will order by the author's name: class Author(models.Model): name = models.CharField() Author.objects.order_by("name")

Is null Django QuerySet?

In Django queryset we have __isnull to check if a value is null. Here were filtering all the values from MyModel model, which have an alias = Null. exclude allows you to pass multiple arguments, it will the then check for every argument. If your query is still more complex, you can use Django's Q Objects.


1 Answers

You can use extra queryset method to select additional data from database table.

This is example that works with MySql:

Person.objects.extra(select={
    'datediff': 'ABS(DATEDIFF(date, NOW()))'}).order_by('datediff')

DATEDIFF - returns difference in days bewteen two dates, ABS - returns absolute value. For sqlite, there is different syntax, 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: closest date after given (todays) date

    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')
like image 183
bmihelac Avatar answered Oct 07 '22 13:10

bmihelac