使用MID()的Python SQLALCHEMY查询
我有一个数据库,正在尝试使用MID()函数查询信息。在普通SQL中,我会使用MID,例如(来自W3示例网站) 将其转换为sqlalchemy是一个挑战。我可以使用分页执行查询,但不能使用mid。到目前为止,我已经完成了 有效的原始查询使用MID()的Python SQLALCHEMY查询,python,sql,flask,sqlalchemy,flask-sqlalchemy,Python,Sql,Flask,Sqlalchemy,Flask Sqlalchemy,我有一个数据库,正在尝试使用MID()函数查询信息。在普通SQL中,我会使用MID,例如(来自W3示例网站) 将其转换为sqlalchemy是一个挑战。我可以使用分页执行查询,但不能使用mid。到目前为止,我已经完成了 有效的原始查询 links = Item.query.filter(Item.title.like('%' +search_term +'%')).paginate(page, 10, True) 将其转换为不起作用 links = Item.query.filter(
links = Item.query.filter(Item.title.like('%' +search_term +'%')).paginate(page, 10, True)
将其转换为不起作用
links = Item.query.filter(func.mid(Item.title.like, 1, 3)('%' +search_term + '%')).paginate(page, 10, True)
TypeError: 'Function' object is not callable
我只需要标题(字符串列)中x-y数量的字符。我可以看到,在中的括号之间缺少一个逗号
,
func.mid(Item.title.like, 1, 3)('%' +search_term + '%')
这使得括号中的第二个表达式成为第一个表达式的参数。这就是异常的来源
TypeError: 'Function' object is not callable.
但是,要生成类似于操作符的,请尝试:
func.mid(Item.title, 1, 3).like('%' +search_term + '%')
这将提供python代码似乎建议的WHERE子句。在您的代码中,类
的放错了位置
但是,如果要生成以下SQL:
SELECT MID(City,1,4) AS ShortCity
FROM Customers;
合适的sqlalchemy代码是
session.query(func.mid(Customer.city, 1, 4).label('ShortCity'))
假设模型名为Customer
,并且有一个名为city
的字段,我可以看到您缺少一个逗号,
,即func.mid(Item.title.like,1,3)('%'+search_-term+'%')
应该是func.mid(Item.title.like,1,3),('%'+search_-term+'%')
。看看这是否解决了问题,这段代码可能还有其他问题,但会遇到typeerror,因为从func.mid(…)返回的对象不可调用,(“%”+搜索项+“%”)
然后被视为函数argumentgives diff error..OperationalError:(sqlite3.OperationalError)靠近“%”:语法错误[SQL:u'SELECT items.id作为items\u id,items.title作为items\u title,items.link作为items\u link,items.member作为items\u member\u since,items.last作为items更新作为items\u last\u updated,items.click作为items计数从items\n点击中间(?,,,,,)和%tor%\n限制偏移量][参数:(,1,3,10,0]啊,可能是这样。我希望搜索词是用户从您的查询不匹配的表单中输入的。在SQLAlchemy查询中,您是否尝试执行MID(title,1,3)像“%something%”
?我是一个noob,但是为什么session.query超过Item.query?我的项目设置错误了吗?不,它们都是有效的,我只是碰巧使用了一个显式的session编写了我的查询。在幕后,sqlalchemy仍然在创建session.links=Item.query(func.mid(Item.title,1,3)。比如(“%”+search_term+“%”)。paginate(第10页,True)TypeError:“BaseQuery”对象不是CallAblinks=Item.query.filter(Item.title.like(“%”+搜索词+“%”)).paginate(第10页,True)您是否尝试过:links=Item.query.filter(func.mid(Item.title,1,4)。like(“%”+搜索词+“%”)。paginate(第10页,True)
,您的代码(返回两条注释)将筛选器表达式作为参数放入查询函数。
session.query(func.mid(Customer.city, 1, 4).label('ShortCity'))