Django order_by query set

Last updated 3 years, 10 months ago | 1894 views 75     5

Tags:- Django

Django | order_by query set, ascending and descending

order_by()

The order_by function is used to sort the result-set in ascending or descending order.


Ascending Order

The order_by function sorts the records in ascending order by default.

Customer.objects.all().order_by('customer_id')
Customer.objects.filter(city="London").order_by('customer_id')

Descending Order

To sort the records in descending order, use a hyphen "-" in front of "check_in".

Customer.objects.all().order_by('-customer_id')
Customer.objects.filter(city="London").order_by('-customer_id')

 

Tips and Tricks


Python In-place swapping of two numbers

 Python | In-place swapping of two numbers

>>> a, b = 10, 20
>>> print(a, b)
10 20

>>> a, b = b, a
>>> print(a, b)
20 10

 


Reversing a String in Python

Python | Reversing a String

>>> x = 'PythonWorld'
>>> print(x[: : -1])
dlroWnohtyP

 


Python join all items of a list to convert into a single string

Python | Join all items of a list to convert into a single string

>>> x = ["Python", "Online", "Training"]
>>> print(" ".join(x))
Python Online Training

 


python return multiple values from functions

Python | Return multiple values from functions

>>> def A():
	return 2, 3, 4

>>> a, b, c = A()

>>> print(a, b, c)
2 3 4

 


Python Print String N times

Python | Print String N times

>>> s = 'Python'
>>> n = 5

>>> print(s * n)
PythonPythonPythonPythonPython