繁体   English   中英

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM