You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WTForms SelectField加载报错TypeError:int()参数类型错误

解决WTForms SelectField加载时的TypeError错误

问题原因

你遇到的TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Row'错误,核心是SelectField的choices属性格式不匹配:

  • WTForms的SelectField要求choices是由**(值, 显示文本)**组成的元组列表,其中第一个元素会被coerce=int转换为整数类型。
  • 你当前用db.session.query(Song.id,Song.title).filter(...).all()获取的是SQLAlchemy的Row对象列表,而非符合要求的元组列表。WTForms尝试将Row对象转为int时,直接触发类型错误。

解决方法

把查询返回的Row对象列表转换为二元组列表即可,修改路由中的对应代码:

原代码:

form.song.choices = (db.session.query(Song.id,Song.title).filter(Song.id.notin_(curr_on_playlist)).all())

修改后:

form.song.choices = [(row.id, row.title) for row in db.session.query(Song.id, Song.title).filter(Song.id.notin_(curr_on_playlist)).all()]

原理说明

  • 列表推导式遍历查询返回的每一个Row对象,提取id和title组成二元组,完全匹配SelectField对choices的格式要求。
  • 表单提交时,form.song.data会被coerce=int转换为整数类型的歌曲ID,能直接用于后续创建PlaylistSong的逻辑。

内容的提问来源于stack exchange,提问作者Owen Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 20:24:51