【问题标题】:SQLALchemy query not returning column's values (sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.str' is not mapped)SQLALchemy 查询不返回列的值(sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.str' is not mapped)
【发布时间】:2021-01-19 03:40:40
【问题描述】:

我正在尝试将 SQLAlchemy 的查询结果附加到列表中。

我的应用程序包含以下模型 ("Game)" 和 games_query(用作 FlaskForm 的 QuerySelectField query_factory)。 编辑:还添加了 FlaskForm,因为问题似乎与表单本身有关,而不是 query_factory。

class Game(db.Model):
   game_id = db.Column(db.Integer, primary_key=True, nullable=False)
   title = db.Column(db.String, nullable=False, unique=True)
   records = db.relationship('Record', backref='game')

def games_query():
   games_list = []
   for g in Game.query:
      games_list.append(g.title)
      print(g.title)
   return games_list

class ScoreForm(FlaskForm):
    name = StringField('Name', validators=[InputRequired()])
    score = IntegerField('Score', validators=[InputRequired()])
    game = QuerySelectField('Game', query_factory=games_query)
    submit = SubmitField('Submit')

games_query 返回以下错误,尽管在控制台中打印 g.title 返回有效值(游戏标题):

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.str' is not 映射

编辑:将 query_factory 设置为返回基本列表的函数会导致显示相同的错误。

def games_query():
    games_list = ["Mario", "Zelda"]
    return games_list

我怎样才能绕过这个错误,所以 games_query 返回可以作为选项传递给相关表单字段的游戏名称列表?

【问题讨论】:

  • 更新了最初的帖子,因为我意识到错误与 FlaskForm 而不是 query_factory 有关。

标签: python flask sqlalchemy flask-sqlalchemy flask-wtforms


【解决方案1】:

我找到了导致错误的原因。解决方法如下。

query_factory 函数应该只返回完整的查询(不是列表,也不是查询的单列):

def games_query():
    return db.session.query(Game)

FlaskForm相关的Jinja代码默认会显示primary_key列,除非会使用get_label属性在FlaskForm中设置特定列:

class ScoreForm(FlaskForm):
    name = StringField('Name', validators=[InputRequired()])
    score = IntegerField('Score', validators=[InputRequired()])
    game = QuerySelectField('Game', query_factory=games_query, get_label='title')
    submit = SubmitField('Submit')

【讨论】:

    【解决方案2】:
    def games_query():
       games_list = []
       for row in Game.query:
          games_list.append(row.__dict__['title'])
          print(row.__dict__['title'])
       return games_list
    
    

    试试看

    【讨论】:

    • 感谢您的帮助,但在您的解决方案中,我收到了完全相同的错误消息(“Class 'builtins.str' is not mapped”)。
    • 哦,我有同样的代码,但运行良好,检查模型,并添加:tablename = 'Game'。
    猜你喜欢
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2015-04-21
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多