【问题标题】:"MySQLInterfaceError: Python type list cannot be converted" on all sqlalchemy.orm.Query methods所有 sqlalchemy.orm.Query 方法上的“MySQLInterfaceError:无法转换 Python 类型列表”
【发布时间】:2021-12-02 13:36:00
【问题描述】:

我正在通过 uvicorn 运行 Python 3.9.0 服务器,其中 sqlalchemy 连接到 mysql 服务器。

我正在尝试使用我构造的 db(会话)对象进行查询,基于我从文档和网络中提取的示例:

database.py

from sqlalchemy.orm import sessionmaker
...
engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    connect_args={'auth_plugin': 'mysql_native_password'}
)
...
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

main.py

from sqlalchemy.orm import Session
from .database import SessionLocal, engine, Base

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

根据docs,我正在尝试调用如下查询:

main.py

db.query(models.OriginalSong).filter_by(original_song_title=original_song_title).first()

但是,first()all() 等方法会抛出相同的错误:

_mysql_connector.MySQLInterfaceError: Python type list cannot be converted

指向调用all()first() 方法的行。

我检查了调用的类型,它们似乎是正确的:

print(type(db.query(models.OriginalSong).filter_by(original_song_title=original_song_title)))

<class 'sqlalchemy.orm.query.Query'>

我不明白我在做什么与docs on the query typetutorial 不同。我发现有一个stackoverflow question 有同样的错误,但尝试加入“列表”却导致同样的错误。我什至不确定first()one() 的返回类型是什么,因为在尝试打印类型之前会出错。

如何访问查询结果而不出错?

(我试图只包含必要的代码,但完整的 repo 可以在 github 上看到)

编辑:奇怪的是,先前的查询有效:

query = db.query(models.RemixArtist).filter_by(remix_artist_name=remix_artist_name).first()

我看不出两者有什么区别。

【问题讨论】:

    标签: python mysql sqlalchemy


    【解决方案1】:

    问题不在于查询的返回,而在于传递给filter_by 的参数。不知不觉中,我给它传递了一个list,而它预期的是string。我必须将参数original_song_title 的参数值更改为original_song_title[0]

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 2021-12-31
      • 2021-12-24
      • 2015-08-27
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 2021-11-14
      相关资源
      最近更新 更多