sqlmodel:sqlalchemy.exc.argumentError:列表达式或从期望的子句,

发布于 2025-01-21 08:49:07 字数 1190 浏览 8 评论 0 原文

我正在使用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'>。

I am using the SQLModel library to do a simple select() like described on their official website. However I am getting Column expression or FROM clause expected error message

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()

this is my models/Hero.py code:

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
     

when I run app.py I get the sqlalchemy.exc.ArgumentError: Column expression or FROM clause expected, got <module 'models.Hero' from '/Users/dev/test/models/Hero.py'>. message

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

明月夜 2025-01-28 08:49:07

错误消息列列表达式或从“预期子句”中,从'/users/dev/dev/test/models/hero.py.py'> 告诉我们:

  • sqlalchemy/sqlmodel < EM>预期要接收列表达式或从子句中:在ORM层中,这通常意味着模型类或模型列的集合被期望
  • SQLALCHEMY/SQLMODEL 意外地收到了一个名为<的模块对象。 Code> Models.Hero
  • 您的模块名为 here.py.py

解决方案是替换对象,导致错误,而 select> select 查询函数期望接收,例如sqlalchemy或sqlmodel orm模型类。

导入语句来自模型导入英雄仅导入模块 英雄。要么

  • 更改导入模型*的导入
     来自Models.Hero Import Hero
     
  • select_heroes 中更改代码以引用模型
     语句= select(here.hero)
     

*它是常规使用所有小写用于模块名称;遵循本惯例将帮助您区分模块和模型。

†我认为这种方法是可取的:通过模块名称空间访问对象可以消除名称碰撞的可能性(当然可以将其与小写模块名称结合使用)。

The error message <Column expression or FROM clause expected, got module 'models.Hero' from '/Users/dev/test/models/Hero.py'> tells us:

  • SQLAlchemy / SQLModel expected to receive a Column expression or FROM clause: in the ORM layer this often means a model class or collection of model's columns was expected
  • SQLAlchemy / SQLModel unexpectedly received a module object named models.Hero
  • that you have a module named Hero.py

The solution is to replace the object causing the error with something that the select or query function would expect to receive, such as an SQLAlchemy or SQLModel ORM model class.

The import statement from models import Hero only imports the module Hero. Either

  • change the import to import the model*
    from models.Hero import Hero
    
  • change the code in select_heroes to reference the model
    statement = select(Hero.Hero)
    

* 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).

呆° 2025-01-28 08:49:07

我之所以得到这个,是因为我忘记了在模型中继承基类。

我的模型是:

class WeatherData:
   __tablename__ = "weather_data"
   ...

然后我只更改为

 Base = declarative_base()

 class WeatherData(Base):
       __tablename__ = "weather_data"

sqlalchemy在:

I got this because I forgot to inherit Base class in my model.

my model was:

class WeatherData:
   __tablename__ = "weather_data"
   ...

Then I only change to

 Base = declarative_base()

 class WeatherData(Base):
       __tablename__ = "weather_data"

sqlalchemy explain this in: https://docs.sqlalchemy.org/en/20/orm/quickstart.html#declare-models

︶葆Ⅱㄣ 2025-01-28 08:49:07

我在下面的脚本上遇到了同样的错误

            from sqlalchemy.sql import select, text
            from dask.dataframe import read_sql_query

            con = "sqlite:///delete_me_test.sqlite"
            query = "SELECT * FROM ticks"
            query2 = " * FROM ticks"

            def _remove_leading_select_from_query(query):
                if query.startswith("SELECT "):
                    return query.replace("SELECT ", "", 1)
                else:
                    return query


            #sa_query = select(text(_remove_leading_select_from_query(query)))
            sa_query = select(text(_remove_leading_select_from_query(query)))
            print(sa_query)
            ddf = read_sql_query(sql=sa_query, con=con, index_col="index")

            print(ddf)
            print(ddf.head(3))    
      

,并通过force降级sqlalchemy版本

pip install --force-reinstall 'sqlalchemy<2.0.0'

>

I got same error with below script

            from sqlalchemy.sql import select, text
            from dask.dataframe import read_sql_query

            con = "sqlite:///delete_me_test.sqlite"
            query = "SELECT * FROM ticks"
            query2 = " * FROM ticks"

            def _remove_leading_select_from_query(query):
                if query.startswith("SELECT "):
                    return query.replace("SELECT ", "", 1)
                else:
                    return query


            #sa_query = select(text(_remove_leading_select_from_query(query)))
            sa_query = select(text(_remove_leading_select_from_query(query)))
            print(sa_query)
            ddf = read_sql_query(sql=sa_query, con=con, index_col="index")

            print(ddf)
            print(ddf.head(3))    
      

and got it fixed by force downgrade sqlalchemy version

pip install --force-reinstall 'sqlalchemy<2.0.0'

ref

桃气十足 2025-01-28 08:49:07

我在两次导入模型类后发现了这个

from app.models.company import CompanyIndustryType
from uuid import UUID
...
from app.schemas.company import CompanyIndustryType

...

for item in data:
                query = select(CompanyIndustryType).where(
                    CompanyIndustryType.id == item.industry_id)
                results = await db.execute(query)
                item.industry = results.scalars().first()

...

错误

Column expression or FROM clause expected, got <class 'app.schemas.company.CompanyIndustryType'>.

对我来说,

For me I got this error after importing the model class twice

from app.models.company import CompanyIndustryType
from uuid import UUID
...
from app.schemas.company import CompanyIndustryType

...

for item in data:
                query = select(CompanyIndustryType).where(
                    CompanyIndustryType.id == item.industry_id)
                results = await db.execute(query)
                item.industry = results.scalars().first()

...

so I got the error

Column expression or FROM clause expected, got <class 'app.schemas.company.CompanyIndustryType'>.

The solution was simply by removing the second import, and everything worked well

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文