sqlalchemy - 为什么我在简单的地质炼金查询中收到 AttributeError InstanceState has no_post_inspect ?

标签 sqlalchemy

尝试查询本地 Postgres 数据库时出现此错误:

发生异常:AttributeError “InstanceState”对象没有属性“_post_inspect”

当我将数据加载到数据库时,连接工作正常。我想我错过了一些愚蠢的事情,但找不到我的错误。我将非常高兴获得任何帮助。

数据库已更新 Postgis,并且应接受形状良好的几何 LineString。 使用的包:

postgresql-14.1-1-windows-x64
postgis_3_1_pg14

GeoAlchemy2 0.10.0
SQLAlchemy 1.4.23
蒸馏器1.7.5
psycopg2 2.9.3

我连接的是:

engine = create_engine(DATABASE_URI)

# 'postgresql+psycopg2://postgres:mypassword@localhost:5432/shapedb'
Session = sessionmaker(bind=engine)

    @contextmanager # helper
    def session_scope():
        session = Session()
        try:
            yield session
            session.commit()
        except Exception:
            session.rollback()
            raise
        finally:
            session.close()

这就是我设置新条目的方式,似乎工作正常):

block1 = BlockPlanSimple(
        geometry = 'MULTILINESTRING((0 0, 21 21, 21 0), (0 0,20 0,20 50,0 50, 0 0))', 
        level = 0,
        room = 'ki',
        roomarea = 23.4,
        scheme_code = '4223_v2',
        house_width = 20.777,
        house_depth = 12.999,
        id_code = '0_v4_12000_99999',
    )


with session_scope() as s:
    # 
    # s.add(block1)
    q1 = s.query(block1).first()
    # print(q1)

模型如下:

Base = declarative_base()
class BlockPlanSimple(Base):
    __tablename__ = 'BlockPlanSimple'
    id = Column(Integer, primary_key=True)
    geometry = Column(Geometry, nullable=False) #?? postgis ->geometry
    # geometry = Column(String, nullable=False) #  postgres ->str
    level = Column(Integer, nullable=False)
    room = Column(String)
    roomarea = Column(Float)
    scheme_code = Column(String(64), index=True, nullable=False)
    house_width = Column(Float, index=True, nullable=False)
    house_depth = Column(Float, index=True, nullable=False)
    id_code = Column(String(64), index=True, unique=True)

完全错误(在 vs 代码中):

发生异常:AttributeError “InstanceState”对象没有属性“_post_inspect” 文件“C:\PyProjects\project2_block_classes_02\crud_shape.py”,第 56 行,位于 q1 = s.query(block1).first()

最佳答案

Session.query() 传递模型类的实例而不是模型类时,会发生此错误:

import sqlalchemy as sa
from sqlalchemy import orm

Base = orm.declarative_base()


class Thing(Base):
    __tablename__ = 't70583312'

    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)


engine = sa.create_engine('postgresql:///test', echo=True, future=True)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
Session = orm.sessionmaker(engine, future=True)

with Session() as s:
    instance_of_thing = Thing(name='Thing 1')
    s.add(instance_of_thing)

    # ↓↓ This should be s.query(Thing)
    s.query(instance_of_thing)

2.0 风格的 select 中出现同样的错误

q = sa.select(instance_of_thing)

这一系列异常的结果:

Traceback (most recent call last):
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/sql/coercions.py", line 183, in expect
    resolved = insp.__clause_element__()
AttributeError: 'InstanceState' object has no attribute '__clause_element__'. Did you mean: 'is_clause_element'?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/python_projects/so38/so70583312.py", line 29, in <module>
    q = sa.select(instance_of_thing)
  File "<string>", line 2, in select
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/sql/selectable.py", line 5281, in _create
    return cls._create_future_select(*args)
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/sql/selectable.py", line 5199, in _create_future_select
    self._raw_columns = [
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/sql/selectable.py", line 5200, in <listcomp>
    coercions.expect(
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/sql/coercions.py", line 185, in expect
    impl._raise_for_expected(original_element, argname)
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/sql/coercions.py", line 437, in _raise_for_expected
    return super(_SelectIsNotFrom, self)._raise_for_expected(
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/sql/coercions.py", line 283, in _raise_for_expected
    util.raise_(exc.ArgumentError(msg, code=code), replace_context=err)
  File "/home/user/virtual-envs/so310/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
    raise exception
sqlalchemy.exc.ArgumentError: Column expression or FROM clause expected, got <__main__.Thing object at 0x7ff53e0f7f70>.

关于sqlalchemy - 为什么我在简单的地质炼金查询中收到 AttributeError InstanceState has no_post_inspect ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70583312/

相关文章:

python - 属性错误 : 'tuple' object has no attribute 'drivername' using Flask SqlAlchemy

python - SQLAlchemy 中 PostgreSQL @> 运算符的等价物是什么

python - SQLAlchemy ORM __init__ 方法与

python - 如何使用Python+SQLAlchemy远程连接MySQL数据库?

python - 在 SQLAlchemy 中,为什么在映射到任意选择时必须为 select 构造别名?

python - 为什么在向数据库添加数据时出现管道损坏错误?

python - 查询多个 between 子句

python - 不同包中的 SQLAlchemy InvalidRequestError

python - Mysql连接池问题: is it worth it?

python - 向 SQLAlchemy 查询添加上下文注释