Search code examples
pythonormpeeweedynamicquery

best way to support dynamic column name and sort direction with peewee python


So far i have something like this:

page_nr = request.query.page_nr
how_many = request.query.how_many
sort_direction = request.query.sort_direction
sort_column = request.query.sort_column

error_urls = Url.select().where((Url.crawl == crawl_id)) \
            .order_by(Url.total_time.desc()) \
            .paginate(int(page_nr), int(how_many)) \
            .dicts()

As you can see, i am not using sort_direction and sort_column. I tried the query below but it did not work.

error_urls = Url.select().where((Url.crawl == crawl_id) & (Url.utype == 'internal')) \
            .order_by(SQL(sort_column).sort_direction()) \
            .paginate(int(page_nr), int(how_many)) \
            .dicts()

(500, 'Internal Server Error', AttributeError("'SQL' object has no attribute 'sort_direction'",), 'Traceback (most recent call last):\n  File "/usr/local/lib/python3.5/dist-packages/bottle.py", line 862, in _handle\n    return route.call(**args)\n  File "/usr/local/lib/python3.5/dist-packages/bottle.py", line 1732, in wrapper\n    rv = callback(*a, **ka)\n  File "index.py", line 55, in _enable_cors\n    return fn(*args, **kwargs)\n  File "index.py", line 383, in get_performance\n    .order_by(SQL(sort_column).sort_direction()) \\\nAttributeError: \'SQL\' object has no attribute \'sort_direction\'\n')

Of course since sort_direction does not seem to be evaled.

What is the best way to achieve dynamic sort_column and sort_direction using the peewee orm? Preferably without writing a raw query, If possible.

Thanks


Solution

  • sort_direction = request.query.sort_direction
    sort_column = request.query.sort_column
    
    error_urls = Url.select().where((Url.crawl == crawl_id)) \
                .order_by(Url.total_time.desc()) \
                .paginate(int(page_nr), int(how_many)) \
                .dicts()
    
    if sort_column not in Url._meta.fields:
        raise Exception('unknown sort column')
    
    field = getattr(Url, sort_column)
    if sort_direction != 'ASC':
        field = field.desc()
    error_urls = error_urls.order_by(field)