我正在尝试根据传递到RESTful Web服务的信息,使用SQLalchemy创建一个可以选择使用过滤和排序的查询。我已经能够在Java中迭代地执行此操作,从一个简单的查询开始并在需要时添加过滤/排序,但我似乎无法在Python中弄清楚。有没有办法做类似的事情:
q = BaseQuery([Image], session)
# Add pagination
q.paginate(page=page, per_page=per_page)
# If present, add filter
if filter is not None:
q.filter(or_(func.lower(Image.description).like('%' + filter + '%'), func.lower(Image.name).like('%' + filter + '%')))
# If present, add sorting
if sortField is not None and sortDir is not None:
if sortDir == 'asc':
q.sort_by(asc(Image.sortField))
elif sortDir == 'desc':
q.sort_by(desc(Image.sortField))
for item in q.items:
print(item)
这样,查询q
是根据UI需要迭代构建的,而不是必须执行大量的if语句来确定它所需的查询大小写。它似乎没有用。
答案 0 :(得分:0)
Per Jon在上面的评论中,这比预期的要容易得多。我只需要重新分配(例如q = q.filter()
)变量:
q = BaseQuery([Image], session)
# If present, add filter
if filter is not None:
q = q.filter(or_(func.lower(Image.description).like('%' + filter + '%'), func.lower(Image.name).like('%' + filter + '%')))
# If present, add sorting
if sortField is not None and sortDir is not None:
if sortDir == 'asc':
q = q.order_by(asc(getattr(Image, sortField)))
elif sortDir == 'desc':
q = q.order_by(desc(getattr(Image, sortField)))
# Add pagination
q = q.paginate(page=page, per_page=per_page)
for item in q.items:
print(item)