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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With