Junior — Middle
How is data sorting performed in Django ORM?
sobes.tech AI
Answer from AI
In Django ORM, data sorting is performed using the order_by() method on a QuerySet. Field names of the model are passed to this method to specify the sorting criteria. By default, sorting is in ascending order. To sort in descending order, a hyphen - is placed before the field name.
Example:
# Sorting users by username in ascending order
users = User.objects.all().order_by('username')
# Sorting users by registration date in descending order
users = User.objects.all().order_by('-date_joined')
Multiple fields can be passed for sorting, in which case sorting is first by the first field, then by the second, and so on.