python - 查询时出现AttributeError : Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute

标签 python sqlalchemy attributeerror

以下代码:

Base = declarative_base()
engine = create_engine(r"sqlite:///" + r"d:\foo.db",
                       listeners=[ForeignKeysListener()])
Session = sessionmaker(bind = engine)
ses = Session()

class Foo(Base):
    __tablename__ = "foo"
    id = Column(Integer, primary_key=True)
    name = Column(String, unique = True)

class Bar(Base):
    __tablename__ = "bar"
    id = Column(Integer, primary_key = True)
    foo_id = Column(Integer, ForeignKey("foo.id"))

    foo = relationship("Foo")


class FooBar(Base):
    __tablename__ = "foobar"
    id = Column(Integer, primary_key = True)
    bar_id = Column(Integer, ForeignKey("bar.id"))

    bar = relationship("Bar")



Base.metadata.create_all(engine)
ses.query(FooBar).filter(FooBar.bar.foo.name == "blah")

给我这个错误:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with FooBar.bar has an attribute 'foo'

任何解释,为什么会发生这种情况,以及如何实现这样的事情的指导?

最佳答案

这是因为您试图从 FooBar 类而不是 FooBar 实例访问 barFooBar 类没有任何与之关联的 bar 对象——bar 只是一个 sqlalchemy InstrumentedAttribute。这就是您收到错误的原因:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with FooBar.bar has an attribute 'foo'

在 sqlalchemy 查询之外输入 FooBar.bar.foo.name 会得到同样的错误。

解决方法是直接调用Foo类:

ses.query(FooBar).join(Bar).join(Foo).filter(Foo.name == "blah")

关于python - 查询时出现AttributeError : Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16589208/

相关文章:

python - 如何将 SqlAlchemy 连接查询序列化为 JSON?

python - AttributeError - 即使似乎没有属性错误

python - 未找到 Shapely parallel_offset

python - 如何在函数内初始化并行独立进程?

python - 对象不是 JSON 可序列化的

python - 在 SELECT 查询之后使 SQLAlchemy COMMIT 而不是 ROLLBACK

python - pickle后属性错误

python - Pandas 是从不同数据帧中添加值计数的更好方法

python - 你如何将 csrf 验证添加到 Pyramid ?

python - 是否可以在 SQLAlchemy 过滤器中使用函数?