AttributeError while querying: Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute

前端 未结 4 1343
旧巷少年郎
旧巷少年郎 2021-01-31 14:33

The following code:

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


        
相关标签:
4条回答
  • 2021-01-31 14:42

    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:

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

    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:

    ses.query(FooBar).join(Bar).join(Foo).filter(Foo.name == "blah")
    
    0 讨论(0)
  • 2021-01-31 14:49

    A related error that can be caused by configuring your SQLAlchemy relationships incorrectly:

    AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'corresponding_column'
    

    In my case, I incorrectly defined a relationship like this:

    namespace   = relationship(PgNamespace, id_namespace, backref="classes")
    

    The id_namespace argument to relationship() should just not be there at all. SQLAlchemy is trying to interpret it as an argument of a different type, and failing with an inscrutable error.

    0 讨论(0)
  • 2021-01-31 14:52

    I cannot explain technically what happens but you can work around this problem by using:

    ses.query(FooBar).join(Foobar.bar).join(Bar.foo).filter(Foo.name == "blah")
    
    0 讨论(0)
  • 2021-01-31 14:59

    I was getting the same error Neither 'InstrumentedAttribute' object nor 'Comparator' has an attribute, but in my case, the problem was my model contained a Column named query, which was overwriting the internal property model.query.

    I decided to rename that Column to query_text and that removed the error. Alternatively, passing the name= argument to the Column method would have worked: query = db.Column(db.TEXT, name='query_text').

    0 讨论(0)
提交回复
热议问题