到目前为止,我有这样的事情:
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的最佳方法是什么?最好不要编写原始查询,如果可能的话。
由于
答案 0 :(得分:2)
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)