2013-05-16 7 views
24

Il seguente codice:AttributeError durante l'interrogazione: oggetto Né 'InstrumentedAttribute' né 'comparatore' ha un attributo

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

mi sta dando questo errore:

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

spiegazioni, perché questo sta succedendo e una guida su come una cosa del genere potrebbe essere raggiunta?

risposta

31

Questo perché si sta tentando di accedere bar dalla classe FooBar piuttosto che un'istanza FooBar. La classe FooBar non ha oggetti bar associati: bar è solo un sqlalchemy InstrumentedAttribute. Questo è il motivo per cui si ottiene l'errore:

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

si otterrà lo stesso errore digitando FooBar.bar.foo.name di fuori della query SQLAlchemy.

La soluzione è quella di chiamare la classe Foo direttamente:

ses.query(FooBar).filter(Foo.name == "blah") 
+11

Cosa succede se la tabella ha più relazioni con 'Foo' ? –

19

non riesco a spiegare tecnicamente cosa succede, ma è possibile aggirare il problema utilizzando:

ses.query(FooBar).join(Foobar.bar).join(Bar.foo).filter(Foo.name == "blah") 
+3

Puoi capire perché funziona nella documentazione: http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#querying-with-joins –

0

un errore correlato che possono essere causati da configurazione delle relazioni SQLAlchemy in modo non corretto:

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

Nel mio caso, ho definito in modo errato un relazione come questa:

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

Il L'argomento id_namespace a relationship() non dovrebbe essere affatto lì. SQLAlchemy sta tentando di interpretarlo come argomento di un tipo diverso e non riuscendo con un errore inscrutabile.