sqlmodel:sqlalchemy.exc.argumentError:列表达式或从期望的子句,
我正在使用SQLModel库来执行简单的 select()
,例如其官方网站上所述。但是,我获得列表达式或从子句期望
错误消息
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
from models import Hero
sqrl = f"mysql+pymysql:///roo@asdf:localhost:3306/datab"
engine = create_engine(sqrl, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def select_heroes():
with Session(engine) as session:
statement = select(Hero)
results = session.exec(statement)
for hero in results:
print(hero)
def main():
select_heroes()
if __name__ == "__main__":
main()
这是我的 models/here.py
代码:
from datetime import datetime, date, time
from typing import Optional
from sqlmodel import Field, SQLModel
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
created: datetime
lastseen: time
运行app.py时,我会获得 sqlalchemy。 exc.ArgumentError:列表达式或从“预期”子句中,从'/users/dev/test/models/momodels/hero.py'>。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
错误消息
列列表达式或从“预期子句”中,从'/users/dev/dev/test/models/hero.py.py'>
告诉我们:here.py.py
解决方案是替换对象,导致错误,而
select> select
或查询
函数期望接收,例如sqlalchemy或sqlmodel orm模型类。导入语句
来自模型导入英雄
仅导入模块英雄
。要么select_heroes
中更改代码以引用模型†*它是常规使用所有小写用于模块名称;遵循本惯例将帮助您区分模块和模型。
†我认为这种方法是可取的:通过模块名称空间访问对象可以消除名称碰撞的可能性(当然可以将其与小写模块名称结合使用)。
The error message
<Column expression or FROM clause expected, got module 'models.Hero' from '/Users/dev/test/models/Hero.py'>
tells us:models.Hero
Hero.py
The solution is to replace the object causing the error with something that the
select
orquery
function would expect to receive, such as an SQLAlchemy or SQLModel ORM model class.The import statement
from models import Hero
only imports the moduleHero
. Eitherselect_heroes
to reference the model†* It's conventional to use all lowercase for module names; following this convention will help you distinguish between modules and models.
† This approach is preferable in my opinion: accessing the object via the module namespace eliminates the possibility of name collisions (of course it can be combined with lowercase module names).
我之所以得到这个,是因为我忘记了在模型中继承基类。
我的模型是:
然后我只更改为
sqlalchemy在:
I got this because I forgot to inherit Base class in my model.
my model was:
Then I only change to
sqlalchemy explain this in: https://docs.sqlalchemy.org/en/20/orm/quickstart.html#declare-models
我在下面的脚本上遇到了同样的错误
,并通过force降级sqlalchemy版本
>
I got same error with below script
and got it fixed by force downgrade sqlalchemy version
ref
我在两次导入模型类后发现了这个
错误
对我来说,
For me I got this error after importing the model class twice
so I got the error
The solution was simply by removing the second import, and everything worked well