Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django order_by, multiple fields and with prioritisation

Tags:

django

I want to sort a QuerySet based on two factors. A and B, but it should prioritise A over B. That is that it should sort on A, but if A is equal for two objects in the QuerySet, it should sort sort those two objects on factor B.

For example, if factor A is time_to_event, and factor B is price. Then it should list all objects with the smallest time_to_event, but if they are the same for two or more objects, it should sort by its price.

I have no code examples since I have not tried anything, although I tried to google with no satisfying results.

like image 888
Alien13 Avatar asked Jul 23 '18 16:07

Alien13


Video Answer


1 Answers

A model manager has the order_by method, that takes a list of fields to be used when sorting a query. Example:

Entry.objects.order_by('-pub_date', 'headline')

The result above will be ordered by pub_date descending, then by headline ascending. The negative sign in front of "-pub_date" indicates descending order.

https://docs.djangoproject.com/en/2.0/ref/models/querysets/#order-by

like image 125
ignacio.munizaga Avatar answered Sep 21 '22 05:09

ignacio.munizaga