David542
David542

Reputation: 110093

Better way to do conditional django queries

Is there a better way to do the following:

    if column_sort == 'size':
        if sort == 'desc':
            results = results.order_by('-size')
        else:
            results = results.order_by('size')
    elif column_sort == 'modified':
        if sort == 'desc':
            results = results.order_by('-last_modified')
        else:
            results = results.order_by('last_modified')
    else:
        if sort == 'desc':
            results = results.order_by('-path')
        else:
            results = results.order_by('path')
    results = results[:100]

For example, a way in which to reverse the query order?

Upvotes: 0

Views: 163

Answers (3)

l4mpi
l4mpi

Reputation: 5149

A better way would be to use a dict to map the values of column_sort:

d = {'size': 'size',
     'modified': 'last_modified',
     #... add more items as needed
    }

Now you just need to call get on the dict, with the second argument specifying a default if the value of column_sort isn't in the dictionary:

orderby = d.get(column_sort, "path")

For the sort variable, just add the '-' as neccessary:

orderby = '-' + orderby if sort == "desc" else orderby

And now just execute it:

results = results.order_by(orderby)

Upvotes: 1

Bartosz
Bartosz

Reputation: 6193

This should word:

columns = dict(size='size', modified='last_modified')
column_sort = columns.get(column_sort, 'path')
order = lambda v: '-' if v == 'desc' else ''
results.order_by(order(sort) + column_sort)

It will translate user-specified column name to your schema and assume that the default is 'path'.

Upvotes: 0

How about you just write the code once?

valid_column_sorts = ['size', 'last_modified', 'path']

if column_sort in valid_column_sorts:
    if sort == 'desc':
        column_sort = '-' + column_sort
    results = results.order_by(column_sort)

Oh yeah, I see that there's some difference between sort fields and values, in which case you need a simple map, like results.order_by(col_map[column_sort])

Upvotes: 2

Related Questions