Conditional order_by in Django ORM

I tend to forget this simple solution so this post is mostly for myself.

In the Django ORM, we are using order_by to sort results of the query by one or multiple columns. In my case this is something like:

[...].order_by('date', 'amount')

Some of the queries are executed in the result of the form submission. This form contains also information about the sort order required by the client. For safety reasons, I don’t pass form fields directly to the order_by clause. In most cases I’m using a simple construction like this:

# default value
sort_order = ['date', 'amount']

if form_sort_field == 'amount':
    sort_order = ['amount', 'date']
elif form_soft_field == '-amount':
    sort_order = ['-amount', 'date']

# and later on
[...].order_by(*sort_order)

This way I’m sure that the default sort is set and if the proper sorting option is sent by the form, the order_by receives the adjusted sort parameters.

Leave a Reply

Your email address will not be published. Required fields are marked *