【问题标题】:Python SQLALCHEMY query using MID()使用 MID() 的 Python SQLALCHEMY 查询
【发布时间】:2016-05-30 17:32:50
【问题描述】:

我有一个数据库,正在尝试使用 MID() 函数查询信息。在普通 SQL 中,我会使用 MID,例如(来自 W3 示例网站)..

SELECT MID(City,1,4) AS ShortCity
FROM Customers; 

将其转换为 sqlalchemy 有点挑战。我可以使用分页执行查询,但不能使用 mid。到目前为止我有 有效的原始查询..

   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 + '%') 应该是func.mid(Item.title.like, 1, 3), ('%' +search_term + '%')。看看是否解决了问题,这段代码可能还有其他问题,但是遇到 typeerror 因为从 func.mid(...) 返回的对象不可调用,然后将('%' +search_term+'%') 视为函数参数跨度>
  • 给出差异错误..
  • OperationalError: (sqlite3.OperationalError) near "%": 语法错误 [SQL: u'SELECT items.id AS items_id, items.title AS items_title, items.link AS items_link, items.description AS items_description, items.member_since AS items_member_since, items.last_updated AS items_last_updated, items.click_count AS items_click_count \nFROM items \nWHERE mid(?, ?, ?) AND %tor%\n LIMIT ? OFFSET ?'] [parameters: (>, 1, 3, 10, 0)]
  • 啊,可能是这样..我希望搜索词是用户从表单输入的
  • 您的查询不匹配。在您的 SQLAlchemy 查询中,您是否尝试执行 MID(title, 1, 3) LIKE '%something%'

标签: python sql flask sqlalchemy flask-sqlalchemy


【解决方案1】:

我可以看到您在括号中缺少逗号 ,

func.mid(Item.title.like, 1, 3)('%' +search_term + '%')

使括号中的第二个表达式成为第一个表达式的参数。这就是异常的根源

TypeError: 'Function' object is not callable.

但是,要生成LIKE 运算符,请尝试:

func.mid(Item.title, 1, 3).like('%' +search_term + '%')

这为您提供了您的 python 代码似乎建议的 WHERE 子句。 在您的代码中,like 放错了位置。

但是,如果您想生成以下 SQL:

SELECT MID(City,1,4) AS ShortCity
FROM Customers; 

适当的 sqlalchemy 代码是

session.query(func.mid(Customer.city, 1, 4).label('ShortCity'))

假设模型名为 Customer 并有一个名为 city 的字段。

【讨论】:

  • 我是个菜鸟,但为什么 session.query 优于 Item.query?我的项目设置错了吗?
  • 不,它们都是有效的,我只是发生明确地使用会话编写我的查询。在幕后,sqlalchemy 仍在创建会话。
  • links = Item.query(func.mid(Item.title, 1, 3).like('%' +search_term + '%')).paginate(page, 10, True) TypeError : 'BaseQuery' 对象不可调用
  • links = Item.query.filter(Item.title.like('%' +search_term + '%')).paginate(page, 10, True)
  • 您尝试过吗:links = Item.query.filter(func.mid(Item.title, 1, 4).like('%' +search_term + '%')).paginate(page, 10, True),您的代码(两个 cmets 后面)将过滤器表达式作为查询函数的参数。
猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
相关资源
最近更新 更多