使用 peewee python 支持动态列名和排序方向的最佳方式

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

到目前为止我有这样的东西:

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()

如您所见,我没有使用 sort_direction 和 sort_column。 我尝试了下面的查询,但没有成功。

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')

当然,因为 sort_direction 似乎没有被评估。

使用 peewee orm 实现动态 sort_column 和 sort_direction 的最佳方法是什么?最好不要编写原始查询,如果可能的话。

谢谢

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)