The following code:
JavaScript
x
31
31
1
Base = declarative_base()
2
engine = create_engine(r"sqlite:///" + r"d:foo.db",
3
listeners=[ForeignKeysListener()])
4
Session = sessionmaker(bind = engine)
5
ses = Session()
6
7
class Foo(Base):
8
__tablename__ = "foo"
9
id = Column(Integer, primary_key=True)
10
name = Column(String, unique = True)
11
12
class Bar(Base):
13
__tablename__ = "bar"
14
id = Column(Integer, primary_key = True)
15
foo_id = Column(Integer, ForeignKey("foo.id"))
16
17
foo = relationship("Foo")
18
19
20
class FooBar(Base):
21
__tablename__ = "foobar"
22
id = Column(Integer, primary_key = True)
23
bar_id = Column(Integer, ForeignKey("bar.id"))
24
25
bar = relationship("Bar")
26
27
28
29
Base.metadata.create_all(engine)
30
ses.query(FooBar).filter(FooBar.bar.foo.name == "blah")
31
is giving me this error:
JavaScript
1
2
1
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with FooBar.bar has an attribute 'foo'
2
Any explanations, as to why this is happening, and guidance to how such a thing could be achieved?
Advertisement
Answer
This is because you are trying to access bar
from the FooBar
class rather than a FooBar
instance. The FooBar
class does not have any bar
objects associated with it–bar
is just an sqlalchemy InstrumentedAttribute. This is why you get the error:
JavaScript
1
2
1
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with FooBar.bar has an attribute 'foo'
2
You will get the same error by typing FooBar.bar.foo.name
outside the sqlalchemy query.
The solution is to call the Foo
class directly:
JavaScript
1
2
1
ses.query(FooBar).join(Bar).join(Foo).filter(Foo.name == "blah")
2