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
相关产品推荐
相关产品推荐

