Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: 'Table' object has no attribute 'id'

I'm a new learner on Python and SQLAlchemy, and I met a curious problem as below.

user = Table('users', meta, autoload=True, autoload_with=engine)

then I

print(user.columns)

it works fine, the output are user.ID, user.Name, etc. But then:

Session = sessionmaker(bind=engine)
session = Session()

session.query(user).order_by(user.id)

shows error:

AttributeError: 'Table' object has no attribute 'id'

I change the "id" to "Name", it's the same error. I also tried the filter_by method, the same error.

Why this happened?

like image 721
Wang Frank Avatar asked Aug 18 '15 08:08

Wang Frank


2 Answers

You could use:

session.query(user).order_by(user.c.id)
like image 128
architectonic Avatar answered Nov 10 '22 17:11

architectonic


Since this is the top answer when you search for this error, I will drop my solution for this as well here.

For my problem, I had to reference the class instead of the table in my models remote_side

so it had to be "Transaction.id" instead of transactions.id

class Transaction(Base):
    __tablename__ = "transactions"
    ...
    
    offset_transaction = relationship(
        ...
        remote_side="Transaction.id",
    )
    ...

like image 1
shiny Avatar answered Nov 10 '22 16:11

shiny