[python] django order_by query set, ascending and descending

How can I order by descending my query set in django by date?

Reserved.objects.all().filter(client=client_id).order_by('check_in')

I just want to filter from descending all the Reserved by check_in date.

This question is related to python django sorting

The answer is


Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.

We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters


If for some reason you have null values you can use the F function like this:

from django.db.models import F

Reserved.objects.all().filter(client=client_id).order_by(F('check_in').desc(nulls_last=True))

So it will put last the null values. Documentation by Django: https://docs.djangoproject.com/en/stable/ref/models/expressions/#using-f-to-sort-null-values


You can also use the following instruction:

Reserved.objects.filter(client=client_id).order_by('check_in').reverse()

  1. Ascending order

    Reserved.objects.all().filter(client=client_id).order_by('check_in')
    
  2. Descending order

    Reserved.objects.all().filter(client=client_id).order_by('-check_in')
    

- (hyphen) is used to indicate descending order here.


Reserved.objects.filter(client=client_id).earliest('check_in')

Or alternatively

Reserved.objects.filter(client=client_id).latest('-check_in')

Here is the documentations for earliest() and latest()


Adding the - will order it in descending order. You can also set this by adding a default ordering to the meta of your model. This will mean that when you do a query you just do MyModel.objects.all() and it will come out in the correct order.

class MyModel(models.Model):

    check_in = models.DateField()

    class Meta:
        ordering = ('-check_in',)

This is working for me.

latestsetuplist = SetupTemplate.objects.order_by('-creationTime')[:10][::1]

It works removing .all():

Reserved.objects.filter(client=client_id).order_by('-check_in')

for ascending order:

Reserved.objects.filter(client=client_id).order_by('check_in')

for descending order:

1.  Reserved.objects.filter(client=client_id).order_by('-check_in')

or

2.  Reserved.objects.filter(client=client_id).order_by('check_in')[::-1]

67

Reserved.objects.filter(client=client_id).order_by('-check_in')

'-' is indicates Descending order and for Ascending order just give class attribute


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically